9511_workbook

solved exercises from algorithms & programming I (9511) prof. Cardozo
Index Commits Files Refs README
commit 443d752c38696c6eb3d26cbd22f537b8c0b6dd41
parent 8ae5186f8848c35104303b8c99146f0b80fac586
Author: klewer-martin <martin.cachari@gmail.com>
Date:   Wed, 23 Jun 2021 01:52:53 -0300

Update: added fread_line(FILE *stream) which is an updated version of function read_line(void)

Diffstat:
Aguia08/a.out | 0
Mguia08/ex17.c | 29+++++++++++++++++++++++++----
2 files changed, 25 insertions(+), 4 deletions(-)
diff --git a/guia08/a.out b/guia08/a.out
Binary files differ.
diff --git a/guia08/ex17.c b/guia08/ex17.c
@@ -5,12 +5,13 @@
 #define GROWTH_FACTOR .5
 
 char *read_line(void);
+char *fread_line(FILE *);
 
 int main (void)
 {
     char *str = NULL;
 
-    str = read_line();
+    str = fread_line(stdin);
     printf("%s", str);
 
     free(str);
@@ -26,15 +27,35 @@ char *read_line(void)
     alloc_size = INIT_SIZE;
 
     if(!(dst = (char *)calloc(alloc_size, sizeof(char)))) return NULL;
-    printf("allocating: %ld bytes\n", alloc_size * sizeof(char));
 
     for(i = 0; (aux = fgetc(stdin)) != EOF; i++)
     {
         if(i == (alloc_size - 2))
         {
-            printf("\nReallocating\ni: %ld\nold size: %ld\n", i, alloc_size);
             alloc_size += (alloc_size * GROWTH_FACTOR);
-            printf("new size: %ld\n", alloc_size);
+            if(!(dst = (char *)realloc(dst, alloc_size * sizeof(char)))) return NULL;
+            for(size_t j = i; j < alloc_size; j++) dst[j] = '\0';
+        }
+        dst[i] = aux;
+    }
+    return dst;
+}
+
+char *fread_line(FILE *fp)
+{
+    char *dst;
+    int aux;
+    size_t i, alloc_size;
+
+    alloc_size = INIT_SIZE;
+
+    if(!(dst = (char *)calloc(alloc_size, sizeof(char)))) return NULL;
+
+    for(i = 0; (aux = fgetc(fp)) != EOF; i++)
+    {
+        if(i == (alloc_size - 2))
+        {
+            alloc_size += (alloc_size * GROWTH_FACTOR);
             if(!(dst = (char *)realloc(dst, alloc_size * sizeof(char)))) return NULL;
             for(size_t j = i; j < alloc_size; j++) dst[j] = '\0';
         }