9511_workbook

solved exercises from algorithms & programming I (9511) prof. Cardozo
Index Commits Files Refs README
guia08/ex18.c (936B)
   1 #include <stdio.h>
   2 #include <stdlib.h>
   3 
   4 #define INIT_SIZE 10
   5 #define GROWTH_FACTOR .5
   6 
   7 typedef enum {
   8     OK,
   9     ERROR_ALLOC_MEMORY,
  10     ERROR_NULL_POINTER
  11 } status_t;
  12 
  13 status_t fread_line(FILE *, char **);
  14 
  15 int main (void)
  16 {
  17     char *str;
  18 
  19     fread_line(stdin, &str);
  20     printf("%s", str);
  21 
  22     free(str);
  23     return 0;
  24 }
  25 
  26 status_t fread_line(FILE *fp, char **dst)
  27 {
  28     int aux;
  29     size_t i, alloc_size;
  30 
  31     if(!dst || !fp) return ERROR_NULL_POINTER;
  32 
  33     alloc_size = INIT_SIZE;
  34 
  35     if(!(*dst = (char *)calloc(alloc_size, sizeof(char)))) return ERROR_ALLOC_MEMORY;
  36 
  37     for(i = 0; (aux = fgetc(fp)) != EOF; i++)
  38     {
  39         if(i == (alloc_size - 2))
  40         {
  41             alloc_size += (alloc_size * GROWTH_FACTOR);
  42             if(!(*dst = (char *)realloc(*dst, alloc_size * sizeof(char)))) return ERROR_ALLOC_MEMORY;
  43             /* Fills the new memory with zeros to avoid valgrind uninitialized warning */
  44             for(size_t j = i; j < alloc_size; j++) (*dst)[j] = '\0';
  45         }
  46         (*dst)[i] = aux;
  47     }
  48     return OK;
  49 }