Advertisement
tdudzik

Untitled

Feb 7th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.39 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. char *readline() {
  5.     int max_size = 10;
  6.  
  7.     int size;
  8.     char c;
  9.     char *line;
  10.  
  11.     size = 0;
  12.     line = malloc(sizeof(*line) * (max_size + 1));
  13.     if (!line) {
  14.         return NULL;
  15.     }
  16.  
  17.     for (;;) {
  18.         if (size == max_size) {
  19.             max_size *= 2;
  20.             line = realloc(line, sizeof(*line) * (max_size + 1));
  21.  
  22.             if (!line) {
  23.                 return NULL;
  24.             }
  25.         }
  26.  
  27.         c = getchar();
  28.         if (c == EOF) {
  29.             return EOF;
  30.         }
  31.  
  32.         if (c == '\n') {
  33.             break;
  34.         }
  35.  
  36.         line[size++] = c;
  37.     }
  38.     line[size] = '\0';
  39.  
  40.     return line;
  41. }
  42.  
  43. char **readlines(int *lines_count) {
  44.     char **lines = malloc(sizeof(*lines) * 10);
  45.  
  46.     int size;
  47.     char *line;
  48.  
  49.     size = 0;
  50.     while ((line = readline()) != EOF) {
  51.         lines[size++] = line;
  52.     }
  53.  
  54.     *lines_count = size;
  55.     return lines;
  56. }
  57.  
  58. void printline(char *line) {
  59.     char c;
  60.     while ((c = *(line++)) != '\0') {
  61.         putchar(c);
  62.     }
  63.  
  64.     putchar('\n');
  65. }
  66.  
  67. void printlines(char **lines, int lines_count) {
  68.     for (int i = 0; i < lines_count; i++) {
  69.         printline(lines[i]);
  70.     }
  71. }
  72.  
  73. int main() {
  74.     int lines_count;
  75.     char **lines;
  76.  
  77.     lines = readlines(&lines_count);
  78.     printlines(lines, lines_count);
  79.  
  80.     free(lines);
  81.  
  82.     return 0;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement