Advertisement
pasholnahuy

Untitled

Dec 17th, 2023 (edited)
878
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.46 KB | None | 0 0
  1. #include "attachments/read_file.h"
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4.  
  5. struct FileContent read_file(int fd) {
  6.     struct FileContent result;
  7.     char *buf = calloc(4096, 1);
  8.     if (buf == NULL) {
  9.         result.size = -1;
  10.         result.data = NULL;
  11.         return result;
  12.     }
  13.     char *cur_buf = buf;
  14.     size_t file_size = 0;
  15.     size_t file_capacity = 4096;
  16.     ssize_t read_res = read(fd, cur_buf, file_capacity);
  17.     while (read_res > 0) {
  18.         file_size += read_res;
  19.         cur_buf += read_res;
  20.         if (file_size == file_capacity) {
  21.             file_capacity <<= 1;
  22.             char *new_buf = realloc(buf, file_capacity);
  23.             if (new_buf == NULL) {
  24.                 free(buf);
  25.                 result.size = -1;
  26.                 result.data = NULL;
  27.                 return result;
  28.             }
  29.             buf = new_buf;
  30.             cur_buf = buf + file_size;
  31.         }
  32.         read_res = read(fd, cur_buf, file_capacity - file_size);
  33.     }
  34.  
  35.     if (read_res == 0) {
  36.         *cur_buf = 0;
  37.         result.size = file_size;
  38.         result.data = buf;
  39.         return result;
  40.     } else {
  41.         result.size = -1;
  42.         result.data = NULL;
  43.         return result;
  44.     }
  45. }
  46.  
  47. #include <fcntl.h>
  48. #include <stdio.h>
  49.  
  50. int main(int argc, char *argv[]) {
  51.     struct FileContent file_content = read_file(open(argv[1], O_RDONLY));
  52.     printf("%zu\n%s", file_content.size, file_content.data);
  53.     free(file_content.data);
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement