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