]> git.saurik.com Git - apple/security.git/blob - SecurityTests/cspxutils/genErrorStrings/fileIo.c
Security-57031.1.35.tar.gz
[apple/security.git] / SecurityTests / cspxutils / genErrorStrings / fileIo.c
1 #include <unistd.h>
2 #include <fcntl.h>
3 #include <errno.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <sys/types.h>
7 #include <sys/stat.h>
8 #include "fileIo.h"
9
10 int writeFile(
11 const char *fileName,
12 const unsigned char *bytes,
13 unsigned numBytes)
14 {
15 int rtn;
16 int fd;
17
18 fd = open(fileName, O_RDWR | O_CREAT | O_TRUNC, 0600);
19 if(fd <= 0) {
20 return errno;
21 }
22 rtn = lseek(fd, 0, SEEK_SET);
23 if(rtn < 0) {
24 return errno;
25 }
26 rtn = write(fd, bytes, (size_t)numBytes);
27 if(rtn != (int)numBytes) {
28 if(rtn >= 0) {
29 printf("writeFile: short write\n");
30 }
31 rtn = EIO;
32 }
33 else {
34 rtn = 0;
35 }
36 close(fd);
37 return rtn;
38 }
39
40 /*
41 * Read entire file.
42 */
43 int readFile(
44 const char *fileName,
45 unsigned char **bytes, // mallocd and returned
46 unsigned *numBytes) // returned
47 {
48 int rtn;
49 int fd;
50 char *buf;
51 struct stat sb;
52 unsigned size;
53
54 *numBytes = 0;
55 *bytes = NULL;
56 fd = open(fileName, O_RDONLY, 0);
57 if(fd <= 0) {
58 return errno;
59 }
60 rtn = fstat(fd, &sb);
61 if(rtn) {
62 goto errOut;
63 }
64 size = sb.st_size;
65 buf = (char *)malloc(size);
66 if(buf == NULL) {
67 rtn = ENOMEM;
68 goto errOut;
69 }
70 rtn = lseek(fd, 0, SEEK_SET);
71 if(rtn < 0) {
72 goto errOut;
73 }
74 rtn = read(fd, buf, (size_t)size);
75 if(rtn != (int)size) {
76 if(rtn >= 0) {
77 printf("readFile: short read\n");
78 }
79 rtn = EIO;
80 }
81 else {
82 rtn = 0;
83 *bytes = (unsigned char *)buf;
84 *numBytes = size;
85 }
86 errOut:
87 close(fd);
88 return rtn;
89 }