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 10int cspWriteFile( 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 */ 43int cspReadFile( 44 const char *fileName, 45 unsigned char **bytes, // mallocd and returned 46 unsigned *numBytes) // returned 47{ 48 int ourRtn = 0; 49 int fd; 50 char *buf; 51 char *thisBuf; 52 struct stat sb; 53 unsigned size; 54 size_t toMove; 55 ssize_t thisMoved; 56 int irtn; 57 off_t lrtn = 0; 58 59 *numBytes = 0; 60 *bytes = NULL; 61 fd = open(fileName, O_RDONLY, 0); 62 if(fd <= 0) { 63 perror("open"); 64 return errno; 65 } 66 irtn = fstat(fd, &sb); 67 if(irtn) { 68 ourRtn = errno; 69 if(ourRtn == 0) { 70 fprintf(stderr, "***Bogus zero error on fstat\n"); 71 ourRtn = -1; 72 } 73 else { 74 perror("fstat"); 75 } 76 goto errOut; 77 } 78 size = sb.st_size; 79 buf = thisBuf = (char *)malloc(size); 80 if(buf == NULL) { 81 ourRtn = ENOMEM; 82 goto errOut; 83 } 84 lrtn = lseek(fd, 0, SEEK_SET); 85 if(lrtn < 0) { 86 ourRtn = errno; 87 if(ourRtn == 0) { 88 fprintf(stderr, "***Bogus zero error on lseek\n"); 89 ourRtn = -1; 90 } 91 else { 92 perror("lseek"); 93 } 94 goto errOut; 95 } 96 toMove = size; 97 98 /* 99 * On ppc this read ALWAYS returns the entire file. On i386, not so. 100 */ 101 do { 102 thisMoved = read(fd, thisBuf, toMove); 103 if(thisMoved == 0) { 104 /* reading empty file: done */ 105 break; 106 } 107 else if(thisMoved < 0) { 108 ourRtn = errno; 109 perror("read"); 110 break; 111 } 112 size_t uThisMoved = (size_t)thisMoved; 113 if(uThisMoved != toMove) { 114 fprintf(stderr, "===Short read: asked for %ld, got %lu\n", 115 toMove, uThisMoved); 116 } 117 toMove -= thisMoved; 118 thisBuf += thisMoved; 119 } while(toMove); 120 121 if(ourRtn == 0) { 122 *bytes = (unsigned char *)buf; 123 *numBytes = size; 124 } 125errOut: 126 close(fd); 127 return ourRtn; 128} 129