1/*
2 * Copyright (c) 2005-2007,2010,2012-2013 Apple Inc. All Rights Reserved.
3 */
4
5#include <unistd.h>
6#include <fcntl.h>
7#include <errno.h>
8#include <stdio.h>
9#include <stdlib.h>
10#include <sys/types.h>
11#include <sys/stat.h>
12#include <stdint.h>
13#include "fileIo.h"
14
15int writeFile(
16	const char			*fileName,
17	const unsigned char	*bytes,
18	size_t              numBytes)
19{
20	int		rtn;
21	int 	fd;
22    ssize_t wrc;
23
24    if (!fileName) {
25        fwrite(bytes, 1, numBytes, stdout);
26        fflush(stdout);
27        return ferror(stdout);
28    }
29
30	fd = open(fileName, O_RDWR | O_CREAT | O_TRUNC, 0600);
31	if(fd <= 0) {
32		return errno;
33	}
34	wrc = write(fd, bytes, (size_t)numBytes);
35	if(wrc != numBytes) {
36		if(wrc >= 0) {
37			fprintf(stderr, "writeFile: short write\n");
38		}
39		rtn = EIO;
40	}
41	else {
42		rtn = 0;
43	}
44	close(fd);
45	return rtn;
46}
47
48/*
49 * Read entire file.
50 */
51int readFile(
52	const char		*fileName,
53	unsigned char	**bytes,		// mallocd and returned
54	size_t          *numBytes)		// returned
55{
56	int rtn;
57	int fd;
58	char *buf;
59	struct stat	sb;
60	size_t size;
61    ssize_t rrc;
62
63	*numBytes = 0;
64	*bytes = NULL;
65	fd = open(fileName, O_RDONLY);
66	if(fd <= 0) {
67		return errno;
68	}
69	rtn = fstat(fd, &sb);
70	if(rtn) {
71		goto errOut;
72	}
73	if (sb.st_size > SIZE_MAX) {
74		rtn = EFBIG;
75		goto errOut;
76	}
77	size = (size_t)sb.st_size;
78	buf = (char *)malloc(size);
79	if(buf == NULL) {
80		rtn = ENOMEM;
81		goto errOut;
82	}
83	rrc = read(fd, buf, size);
84	if(rrc != size) {
85		if(rtn >= 0) {
86            free(buf);
87			fprintf(stderr, "readFile: short read\n");
88		}
89		rtn = EIO;
90	}
91	else {
92		rtn = 0;
93		*bytes = (unsigned char *)buf;
94		*numBytes = size;
95	}
96
97errOut:
98	close(fd);
99	return rtn;
100}
101