]> git.saurik.com Git - apple/security.git/blob - OSX/libsecurity_keychain/libDER/libDERUtils/fileIo.c
Security-57740.31.2.tar.gz
[apple/security.git] / OSX / libsecurity_keychain / libDER / libDERUtils / fileIo.c
1 /*
2 * Copyright (c) 2005-2007,2010-2012 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 "fileIo.h"
13
14 int writeFile(
15 const char *fileName,
16 const unsigned char *bytes,
17 unsigned numBytes)
18 {
19 int rtn;
20 int fd;
21
22 fd = open(fileName, O_RDWR | O_CREAT | O_TRUNC, 0600);
23 if(fd <= 0) {
24 return errno;
25 }
26 rtn = (int)write(fd, bytes, (size_t)numBytes);
27 if(rtn != (int)numBytes) {
28 if(rtn >= 0) {
29 fprintf(stderr, "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 = (unsigned) sb.st_size;
65 buf = (char *)malloc(size);
66 if(buf == NULL) {
67 rtn = ENOMEM;
68 goto errOut;
69 }
70 rtn = (int)read(fd, buf, size);
71 if(rtn != size) {
72 if(rtn >= 0) {
73 fprintf(stderr, "readFile: short read\n");
74 }
75 rtn = EIO;
76 }
77 else {
78 rtn = 0;
79 *bytes = (unsigned char *)buf;
80 *numBytes = size;
81 }
82 errOut:
83 close(fd);
84 return rtn;
85 }