file.c (1819B)
1 #include "file.h" 2 3 #include <fcntl.h> 4 #include <stdlib.h> 5 #include <string.h> 6 #include <unistd.h> 7 8 static int read_fd(int fd, uint8_t **out, size_t *len_out) { 9 size_t cap = 65536; 10 size_t len = 0; 11 uint8_t *buf = malloc(cap + 1); 12 if (!buf) return -1; 13 for (;;) { 14 if (len == cap) { 15 size_t ncap = cap * 2; 16 uint8_t *nbuf = realloc(buf, ncap + 1); 17 if (!nbuf) { 18 free(buf); 19 return -1; 20 } 21 buf = nbuf; 22 cap = ncap; 23 } 24 ssize_t n = read(fd, buf + len, cap - len); 25 if (n < 0) { 26 free(buf); 27 return -1; 28 } 29 if (n == 0) break; 30 len += (size_t)n; 31 } 32 buf[len] = 0; 33 *out = buf; 34 *len_out = len; 35 return 0; 36 } 37 38 static int write_fd(int fd, const uint8_t *data, size_t len) { 39 size_t put = 0; 40 while (put < len) { 41 ssize_t n = write(fd, data + put, len - put); 42 if (n <= 0) return -1; 43 put += (size_t)n; 44 } 45 return 0; 46 } 47 48 int util_file_read(const char *path, uint8_t **out, size_t *len_out) { 49 int fd; 50 int rc; 51 if (!out || !len_out) return -1; 52 if (!path || strcmp(path, "-") == 0) { 53 return read_fd(STDIN_FILENO, out, len_out); 54 } 55 fd = open(path, O_RDONLY); 56 if (fd < 0) return -1; 57 rc = read_fd(fd, out, len_out); 58 close(fd); 59 return rc; 60 } 61 62 int util_file_write(const char *path, const uint8_t *data, size_t len, unsigned mode, int force) { 63 int fd; 64 int rc; 65 int flags = O_WRONLY | O_CREAT | O_TRUNC; 66 if (!data && len) return -1; 67 if (!path || strcmp(path, "-") == 0) { 68 return write_fd(STDOUT_FILENO, data, len); 69 } 70 if (!force) flags |= O_EXCL; 71 fd = open(path, flags, mode); 72 if (fd < 0) return -1; 73 rc = write_fd(fd, data, len); 74 close(fd); 75 return rc; 76 } 77 78 int util_file_exists(const char *path) { 79 if (!path || strcmp(path, "-") == 0) return 0; 80 return access(path, F_OK) == 0; 81 }