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