]> git.saurik.com Git - apple/security.git/blob - OSX/utilities/src/fileIo.c
Security-58286.1.32.tar.gz
[apple/security.git] / OSX / utilities / src / fileIo.c
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
15 int writeFile(
16 const char *fileName,
17 const unsigned char *bytes,
18 unsigned numBytes)
19 {
20 size_t n = numBytes;
21 return writeFileSizet(fileName, bytes, n);
22 }
23
24 int writeFileSizet(
25 const char *fileName,
26 const unsigned char *bytes,
27 size_t numBytes)
28 {
29 int rtn;
30 int fd;
31 ssize_t wrc;
32
33 if (!fileName) {
34 fwrite(bytes, 1, numBytes, stdout);
35 fflush(stdout);
36 return ferror(stdout);
37 }
38
39 fd = open(fileName, O_RDWR | O_CREAT | O_TRUNC, 0600);
40 if(fd == -1) {
41 return errno;
42 }
43 wrc = write(fd, bytes, (size_t)numBytes);
44 if(wrc != (ssize_t) numBytes) {
45 if(wrc >= 0) {
46 fprintf(stderr, "writeFile: short write\n");
47 }
48 rtn = EIO;
49 }
50 else {
51 rtn = 0;
52 }
53 close(fd);
54 return rtn;
55 }
56
57 /*
58 * Read entire file.
59 */
60 int readFileSizet(
61 const char *fileName,
62 unsigned char **bytes, // mallocd and returned
63 size_t *numBytes) // returned
64 {
65 int rtn;
66 int fd;
67 char *buf;
68 struct stat sb;
69 size_t size;
70 ssize_t rrc;
71
72 *numBytes = 0;
73 *bytes = NULL;
74 fd = open(fileName, O_RDONLY);
75 if(fd == -1) {
76 return errno;
77 }
78 rtn = fstat(fd, &sb);
79 if(rtn) {
80 goto errOut;
81 }
82 if (sb.st_size > (off_t) ((UINT32_MAX >> 1)-1)) {
83 rtn = EFBIG;
84 goto errOut;
85 }
86 size = (size_t)sb.st_size;
87 buf = (char *)malloc(size);
88 if(buf == NULL) {
89 rtn = ENOMEM;
90 goto errOut;
91 }
92 rrc = read(fd, buf, size);
93 if(rrc != (ssize_t) size) {
94 if(rtn >= 0) {
95 free(buf);
96 fprintf(stderr, "readFile: short read\n");
97 }
98 rtn = EIO;
99 }
100 else {
101 rtn = 0;
102 *bytes = (unsigned char *)buf;
103 *numBytes = size;
104 }
105
106 errOut:
107 close(fd);
108 return rtn;
109 }