io.c (1246B)
1 2 #include "io.h" 3 4 #include <string.h> 5 #include <sys/stat.h> 6 #include <sys/mman.h> 7 #include <unistd.h> 8 #include <fcntl.h> 9 10 int read_fd(FILE *fd, unsigned char *buf, int buflen, int *written) 11 { 12 unsigned char *p = buf; 13 int len = 0; 14 *written = 0; 15 16 do { 17 len = fread(p, 1, 4096, fd); 18 *written += len; 19 p += len; 20 if (p > buf + buflen) 21 return 0; 22 } while (len == 4096); 23 24 return 1; 25 } 26 27 int map_file(const char *filename, unsigned char **p, size_t *flen) 28 { 29 struct stat st; 30 int des; 31 stat(filename, &st); 32 *flen = st.st_size; 33 34 des = open(filename, O_RDONLY); 35 36 *p = mmap(NULL, *flen, PROT_READ, MAP_PRIVATE, des, 0); 37 close(des); 38 39 return *p != MAP_FAILED; 40 } 41 42 int read_file(const char *filename, unsigned char *buf, int buflen, int *written) 43 { 44 FILE *file = NULL; 45 int ok; 46 47 file = fopen(filename, "r"); 48 if (file == NULL) { 49 *written = strlen(filename)+1; 50 memcpy(buf, filename, *written); 51 buf[*written-1] = '\n'; 52 return 1; 53 } 54 55 ok = read_fd(file, buf, buflen, written); 56 fclose(file); 57 return ok; 58 } 59 60 61 int read_file_or_stdin(const char *filename, unsigned char *buf, int buflen, 62 int *written) 63 { 64 if (filename == NULL) { 65 return read_fd(stdin, buf, buflen, written); 66 } 67 68 return read_file(filename, buf, buflen, written); 69 }