utils.c (762B)
1 #include "asm.h" 2 3 char* read_file(char *filename) { 4 int fd = open(filename, O_RDONLY); 5 if (fd < 0) { 6 perror(PROGRAM_NAME); 7 exit(1); 8 } 9 10 off_t size = lseek(fd, 0, SEEK_END); 11 if (size == -1) { 12 close(fd); 13 return NULL; 14 } 15 lseek(fd, 0, SEEK_SET); 16 17 char *buf = malloc(size + 1); 18 if (!buf) { 19 close(fd); 20 21 perror(PROGRAM_NAME); 22 exit(1); 23 } 24 25 ssize_t total_read = 0; 26 ssize_t bytes_read; 27 while (total_read < size) { 28 bytes_read = read(fd, buf + total_read, size - total_read); 29 if (bytes_read == -1) { 30 free(buf); 31 close(fd); 32 33 perror(PROGRAM_NAME); 34 exit(1); 35 } 36 if (bytes_read == 0) { 37 break; 38 } 39 total_read += bytes_read; 40 } 41 42 buf[size] = '\0'; 43 close(fd); 44 return buf; 45 } 46