Advertisement
Art_Uspen

Untitled

Jan 11th, 2022
740
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.77 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.     char *mystring = malloc(1 * sizeof(char));
  8.     int capacity = 1;
  9.     int len = 0;
  10.     if (!f) {
  11.         return NULL;
  12.     }
  13.     while ((sym = fgetc(f))) {
  14.         if (len == capacity - 1) {
  15.             capacity *= 2;
  16.             char* tmp_mystring = mystring;
  17.             mystring = realloc(tmp_mystring,capacity);
  18.             if(!mystring){
  19.                 return NULL;
  20.             }
  21.         }
  22.         mystring[len] = sym;
  23.         ++len;
  24.         if(sym == '\n'){
  25.             mystring[len] = '\0';
  26.             return mystring;
  27.         }
  28.     }
  29.     if(strlen(mystring) == 0){
  30.         return NULL;
  31.     }
  32.     mystring[len] = '\0';
  33.     return mystring;
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement