9511_workbook

solved exercises from algorithms & programming I (9511) prof. Cardozo
Index Commits Files Refs README
guia08/ex17.c (1204B)
   1 #include <stdio.h>
   2 #include <stdlib.h>
   3 
   4 #define INIT_SIZE 10
   5 #define GROWTH_FACTOR .5
   6 
   7 char *read_line(void);
   8 char *fread_line(FILE *);
   9 
  10 int main (void)
  11 {
  12     char *str = NULL;
  13 
  14     str = fread_line(stdin);
  15     printf("%s", str);
  16 
  17     free(str);
  18     return 0;
  19 }
  20 
  21 char *read_line(void)
  22 {
  23     char *dst;
  24     int aux;
  25     size_t i, alloc_size;
  26 
  27     alloc_size = INIT_SIZE;
  28 
  29     if(!(dst = (char *)calloc(alloc_size, sizeof(char)))) return NULL;
  30 
  31     for(i = 0; (aux = fgetc(stdin)) != EOF; i++)
  32     {
  33         if(i == (alloc_size - 2))
  34         {
  35             alloc_size += (alloc_size * GROWTH_FACTOR);
  36             if(!(dst = (char *)realloc(dst, alloc_size * sizeof(char)))) return NULL;
  37             for(size_t j = i; j < alloc_size; j++) dst[j] = '\0';
  38         }
  39         dst[i] = aux;
  40     }
  41     return dst;
  42 }
  43 
  44 char *fread_line(FILE *fp)
  45 {
  46     char *dst;
  47     int aux;
  48     size_t i, alloc_size;
  49 
  50     if(!fp) return NULL;
  51 
  52     alloc_size = INIT_SIZE;
  53 
  54     if(!(dst = (char *)calloc(alloc_size, sizeof(char)))) return NULL;
  55 
  56     for(i = 0; (aux = fgetc(fp)) != EOF; i++)
  57     {
  58         if(i == (alloc_size - 2))
  59         {
  60             alloc_size += (alloc_size * GROWTH_FACTOR);
  61             if(!(dst = (char *)realloc(dst, alloc_size * sizeof(char)))) return NULL;
  62             for(size_t j = i; j < alloc_size; j++) dst[j] = '\0';
  63         }
  64         dst[i] = aux;
  65     }
  66     return dst;
  67 }