io.c (1782B)
1 2 #include <sys/types.h> 3 #include <sys/stat.h> 4 #include <sys/mman.h> 5 #include <sys/wait.h> 6 #include <unistd.h> 7 #include <fcntl.h> 8 9 #include "io.h" 10 11 int map_file(const char *filename, unsigned char **p, size_t *flen) 12 { 13 struct stat st; 14 int des; 15 stat(filename, &st); 16 *flen = st.st_size; 17 18 des = open(filename, O_RDONLY); 19 20 *p = mmap(NULL, *flen, PROT_READ, MAP_PRIVATE, des, 0); 21 close(des); 22 23 return *p != MAP_FAILED; 24 } 25 26 int write_file(const char *filename, unsigned char *out, size_t len) 27 { 28 FILE *file = NULL; 29 size_t written; 30 31 file = fopen(filename, "wb"); 32 if (file == NULL) { 33 fprintf(stderr, "fopen wb '%s' failed\n", filename); 34 return 0; 35 } 36 37 written = fwrite(out, 1, len, file); 38 39 if (written != len) { 40 fprintf(stderr, "written != len, %ld != %ld\n", written, len); 41 fclose(file); 42 return 0; 43 } 44 45 fclose(file); 46 return 1; 47 } 48 49 int read_fd(FILE *fd, unsigned char *buf, int buflen, int *written) 50 { 51 unsigned char *p = buf; 52 int len = 0; 53 *written = 0; 54 55 do { 56 len = fread(p, 1, 4096, fd); 57 *written += len; 58 p += len; 59 if (p > buf + buflen) 60 return 0; 61 } while (len == 4096); 62 63 return 1; 64 } 65 66 int read_file(const char *filename, unsigned char *out, int out_len, int *written) 67 { 68 FILE *file = NULL; 69 70 file = fopen(filename, "rb"); 71 if (file == NULL) 72 return 0; 73 74 return read_fd(file, out, out_len, written); 75 } 76 77 int dir_exists(const char *path) 78 { 79 struct stat st; 80 81 if (stat(path, &st) == 0 && S_ISDIR(st.st_mode)) { 82 return 1; 83 } 84 85 return 0; 86 } 87 88 // todo: make this less dumb 89 int mkdirp(const char *path) 90 { 91 int status; 92 93 switch (fork()) { 94 case -1: 95 return 0; 96 case 0: 97 /* child, run man command. */ 98 execlp("mkdir", "mkdir", "-p", path, (char *)NULL); 99 return 0; 100 default: 101 break; 102 } 103 104 wait(&status); 105 return WIFEXITED(status) && WEXITSTATUS(status) == 0; 106 }