1/*
2 * Copyright (c) 2001-2003,2006-2012,2014 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24/*
25 * fileIo.c - simple file read/write utilities
26 */
27
28#include <unistd.h>
29#include <fcntl.h>
30#include <errno.h>
31#include <stdio.h>
32#include <stdlib.h>
33#include <sys/types.h>
34#include <sys/stat.h>
35#include "fileIo.h"
36
37int writeFile(
38	const char			*fileName,
39	const unsigned char	*bytes,
40	unsigned			numBytes)
41{
42	int		rtn;
43	int 	fd;
44
45	fd = open(fileName, O_RDWR | O_CREAT | O_TRUNC, 0600);
46	if(fd < 0) {
47		return errno;
48	}
49	rtn = lseek(fd, 0, SEEK_SET);
50	if(rtn < 0) {
51		return errno;
52	}
53	rtn = write(fd, bytes, (size_t)numBytes);
54	if(rtn != (int)numBytes) {
55		if(rtn >= 0) {
56			printf("writeFile: short write\n");
57		}
58		rtn = EIO;
59	}
60	else {
61		rtn = 0;
62	}
63	close(fd);
64	return rtn;
65}
66
67/*
68 * Read entire file.
69 */
70int readFile(
71	const char		*fileName,
72	unsigned char	**bytes,		// mallocd and returned
73	unsigned		*numBytes)		// returned
74{
75	int rtn;
76	int fd;
77	unsigned char *buf;
78	struct stat	sb;
79	unsigned size;
80
81	*numBytes = 0;
82	*bytes = NULL;
83	fd = open(fileName, O_RDONLY, 0);
84	if(fd < 0) {
85		return errno;
86	}
87	rtn = fstat(fd, &sb);
88	if(rtn) {
89		goto errOut;
90	}
91	size = sb.st_size;
92	buf = malloc(size);
93	if(buf == NULL) {
94		rtn = ENOMEM;
95		goto errOut;
96	}
97	rtn = lseek(fd, 0, SEEK_SET);
98	if(rtn < 0) {
99		goto errOut;
100	}
101	rtn = read(fd, buf, (size_t)size);
102	if(rtn != (int)size) {
103		if(rtn >= 0) {
104			printf("readFile: short read\n");
105		}
106		rtn = EIO;
107	}
108	else {
109		rtn = 0;
110		*bytes = buf;
111		*numBytes = size;
112	}
113errOut:
114	close(fd);
115	return rtn;
116}
117