Advertisement
Guest User

Untitled

a guest
Sep 22nd, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.17 KB | None | 0 0
  1. ///
  2. //  main.c
  3. //  ht01_04
  4. //
  5. //  Created by Артем Барышев on 19.09.2018.
  6. //  Copyright © 2018 Артем Барышев. All rights reserved.
  7. //
  8.  
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <errno.h>
  12. #include <string.h>
  13.  
  14. char *getline2(FILE *f) {
  15.     char now;
  16.     char *new_string = malloc(sizeof(now));
  17.     if (new_string == NULL) {
  18.         return NULL;
  19.     }
  20.     size_t size = 0, real_size = 1;
  21.     while ((now = getc_unlocked(f)) != EOF) {
  22.         if (size == real_size) {
  23.             real_size *= 2;
  24.             new_string = realloc(new_string, sizeof(now) * real_size);
  25.             if (new_string == NULL) {
  26.                 return NULL;
  27.             }
  28.         }
  29.         new_string[size] = now;
  30.         size++;
  31.         if (now == '\n') {
  32.             break;
  33.         }
  34.     }
  35.     if (size == 0) {
  36.         return NULL;
  37.     }
  38.     if (size == real_size) {
  39.         real_size++;
  40.         new_string = realloc(new_string, sizeof(now) * real_size);
  41.         if (new_string == NULL) {
  42.             return NULL;
  43.         }
  44.     }
  45.     new_string[size++] = '\0';
  46.     new_string = realloc(new_string, sizeof(now) * size);
  47.     return new_string;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement