Advertisement
STANAANDREY

my getline

Nov 19th, 2022
902
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.78 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define CHUNK 16
  4. #define NULL_CHECK(p) if (p == NULL) return NULL
  5.  
  6. char* stdinGetLine() {
  7.   char *line = NULL, ch;
  8.   int i = 0, currAlloc = 0;
  9.   while ((ch = getchar()) != EOF) {
  10.     if (i == currAlloc) {
  11.       currAlloc += CHUNK;
  12.       line = realloc(line, sizeof(char) * currAlloc);
  13.       NULL_CHECK(line);
  14.     }
  15.     if (ch != '\n') {
  16.       *(line + i) = ch;
  17.     } else {
  18.       break;
  19.     }
  20.     i++;
  21.   }
  22.   if (i == currAlloc) {
  23.     currAlloc++;
  24.     line = realloc(line, sizeof(char) * currAlloc);
  25.   }
  26.  
  27.   NULL_CHECK(line);
  28.  
  29.   *(line + i) = 0;  
  30.   return line;
  31. }
  32.  
  33. int main(void) {
  34.   char *s = stdinGetLine();
  35.   if (s == NULL) {
  36.     perror("Error!");
  37.     return 0;
  38.   }
  39.   puts(s);
  40.   free(s);
  41.   s = NULL;
  42.   return 0;
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement