Advertisement
Art_Uspen

Untitled

Jan 11th, 2022
666
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.35 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.                 if(strlen(mystring) == 0){
  27.                     return NULL;
  28.                 }
  29.                 ++capacity;
  30.                 mystring = (unsigned char*) realloc (mystring,capacity);
  31.                 if(!mystring) {
  32.                     return NULL;
  33.                 }
  34.                 int len = strlen(mystring);
  35.                 mystring[len] = '\0';
  36.                 return mystring;
  37.             } else {
  38.                 return NULL;
  39.             }
  40.         }
  41.  
  42.         int len = strlen(mystring);
  43.         mystring[len] = sym;
  44.  
  45.         ++capacity;
  46.         mystring = (unsigned char*) realloc (mystring,capacity);
  47.         if(!mystring) {
  48.             return NULL;
  49.         }
  50.     }
  51. }
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement