Advertisement
STANAANDREY

read lines c

Dec 16th, 2022
823
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.71 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define NULL_CHECK(p) if (p == NULL) return NULL;
  4. #define CHUNK_CHARS 32
  5. #define CHUNK_POINTERS 8
  6.  
  7. char *readLine(FILE *file) {
  8.   char *line = NULL, ch;
  9.   int index = 0, currSize = 0;
  10.   while ((ch = fgetc(file)) != EOF) {
  11.     if (index == currSize) {
  12.       currSize += CHUNK_CHARS;
  13.       line = realloc(line, sizeof(char) * currSize);
  14.       NULL_CHECK(line);
  15.     }
  16.     if (ch != '\n') {
  17.       line[index++] = ch;
  18.     } else {
  19.       break;
  20.     }
  21.   }
  22.   NULL_CHECK(line);
  23.   if (index == currSize) {
  24.     currSize++;
  25.     line = realloc(line, sizeof(char) * currSize);
  26.   } else {
  27.     currSize = index + 1;
  28.     line = realloc(line, sizeof(char) * currSize);
  29.   }
  30.   NULL_CHECK(line);
  31.   line[index] = 0;
  32.   return line;
  33. }
  34.  
  35. char **readLines(FILE *file) {
  36.   char **lines = NULL, *line = NULL;
  37.   int index = 0, currSize = 0;
  38.   while ((line = readLine(file)) != NULL) {
  39.     if (index == currSize) {
  40.       currSize += CHUNK_POINTERS;
  41.       lines = realloc(lines, sizeof(char*) * currSize);
  42.       NULL_CHECK(lines);
  43.     }
  44.     lines[index++] = line;
  45.   }
  46.   NULL_CHECK(lines);
  47.   if (index == currSize) {
  48.     currSize++;
  49.     lines = realloc(lines, sizeof(char*) * currSize);
  50.   } else {
  51.     currSize = index + 1;
  52.     lines = realloc(lines, sizeof(char*) * currSize);
  53.   }
  54.   NULL_CHECK(lines);
  55.   lines[index] = NULL;
  56.   return lines;
  57. }
  58.  
  59. void free2d(char **p2p) {
  60.   for (int i = 0; p2p[i] != NULL; i++) {
  61.     free(p2p[i]);
  62.   }
  63.   free(p2p);
  64. }
  65.  
  66. void writeLines(char **lines) {
  67.   for (int i = 0; lines[i] != NULL; i++) {
  68.     puts(lines[i]);
  69.   }
  70. }
  71.  
  72. int main(void) {
  73.   char **lines = NULL;
  74.   lines = readLines(stdin);
  75.   writeLines(lines);
  76.   free2d(lines);
  77.   return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement