Advertisement
Art_Uspen

Untitled

Jan 11th, 2022
709
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.32 KB | None | 0 0
  1. char *getline2(FILE *f) {
  2.     int sym;
  3.     unsigned char *mystring = malloc(1 * sizeof(unsigned char));
  4.     int capacity = 1;
  5.     if (f == NULL) {
  6.         return NULL;
  7.     }
  8.     while (1) {
  9.         sym = fgetc(f);
  10.         if (sym == (int) '\n') {
  11.             capacity+=2;
  12.             mystring = (unsigned char*) realloc (mystring,capacity);
  13.             if(!mystring) {
  14.                 return NULL;
  15.             }
  16.             int len = strlen(mystring);
  17.             mystring[len-1] = '\n';
  18.             mystring[len] = '\0';
  19.             return mystring;
  20.         }
  21.         if (sym == EOF) {
  22.             if (feof(f) != 0) {
  23.                 if(strlen(mystring) == 0){
  24.                     return NULL;
  25.                 }
  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.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement