Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.14 KB | None | 0 0
  1. #include <errno.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5.  
  6. #include <fcntl.h>
  7. #include <sys/stat.h>
  8. #include <sys/types.h>
  9. #include <unistd.h>
  10.  
  11. enum { BUFFER_SIZE = 4096 };
  12.  
  13. ssize_t read_BUFF(int in_fd, char *buffer) {
  14.     ssize_t count_read = 0;
  15.     while (count_read != BUFFER_SIZE) {
  16.         ssize_t read_bytes = read(in_fd, buffer + count_read,
  17.             BUFFER_SIZE - count_read);
  18.         if (read_bytes == -1) {
  19.             return -1;
  20.         }
  21.         if (read_bytes == 0) {
  22.             return count_read;
  23.         }
  24.         count_read += read_bytes;  
  25.     }
  26.     return BUFFER_SIZE;
  27. }
  28.  
  29. struct FileContent read_file(int fd) {
  30.     errno = !ENOMEM;
  31.     struct FileContent returned;
  32.     char buffer[BUFFER_SIZE];
  33.  
  34.     char *data = malloc(sizeof(*data));
  35.     if (errno == ENOMEM) {
  36.         free(data);
  37.         returned.size = -1;
  38.         returned.data = NULL;
  39.         return returned;
  40.     }
  41.     size_t cur_mal = 1;
  42.    
  43.     if (data == NULL) {
  44.         free(data);
  45.         returned.size = -1;
  46.         returned.data = NULL;
  47.         return returned;
  48.     }
  49.  
  50.     ssize_t read = 1;
  51.     ssize_t current_read = 0;
  52.     while (read > 0) {
  53.         read = read_BUFF(fd, buffer);
  54.         if (read == -1) {
  55.             free(data);
  56.             returned.size = -1;
  57.             returned.data = NULL;
  58.             return returned;
  59.         }
  60.         while (current_read + read >= cur_mal) {
  61.             char *data1;
  62.             data1 = realloc(data, (cur_mal *= 2) * sizeof(*data));
  63.             if (data1 == NULL) {
  64.                 free(data);
  65.                 returned.size = -1;
  66.                 returned.data = NULL;
  67.                 return returned;
  68.             } else {
  69.                 data = data1;
  70.             }
  71.             if (errno == ENOMEM) {
  72.                 free(data);
  73.                 returned.size = -1;
  74.                 returned.data = NULL;
  75.                 return returned;
  76.             }
  77.         }
  78.         memcpy(data + current_read, buffer, read);
  79.         current_read += read;
  80.     }
  81.     returned.size = current_read;
  82.     data[current_read] = 0;
  83.     returned.data = data;
  84.     return returned;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement