Advertisement
Art_Uspen

Untitled

Jan 11th, 2022
676
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.33 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <malloc.h>
  3. #include <string.h>
  4.  
  5. char *getline2(FILE *f) {
  6.     int sym;
  7.     unsigned char *mystring = malloc(1 * sizeof(unsigned char));
  8.     int capacity = 1;
  9.     if (f == NULL) {
  10.         return NULL;
  11.     }
  12.     while (1) {
  13.         sym = fgetc(f);
  14.         if (sym == (int) '\n') {
  15.             ++capacity;
  16.             mystring = (unsigned char*) realloc (mystring,capacity);
  17.             if(!mystring) {
  18.                 return NULL;
  19.             }
  20.             int len = strlen(mystring);
  21.             mystring[len] = '\0';
  22.             return mystring;
  23.         }
  24.         if (sym == EOF) {
  25.             if (feof(f) != 0) {
  26.                 ++capacity;
  27.                 mystring = (unsigned char*) realloc (mystring,capacity);
  28.                 if(!mystring) {
  29.                     return NULL;
  30.                 }
  31.                 int len = strlen(mystring);
  32.                 mystring[len] = '\0';
  33.                 return mystring;
  34.             } else {
  35.                 return NULL;
  36.             }
  37.         }
  38.  
  39.         int len = strlen(mystring);
  40.         mystring[len] = sym;
  41.  
  42.         ++capacity;
  43.         mystring = (unsigned char*) realloc (mystring,capacity);
  44.         if(!mystring) {
  45.             return NULL;
  46.         }
  47. //        puts(mystring);
  48. //        printf("%c", sym);
  49.     }
  50.     return mystring;
  51. }
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement