fork(1) download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. char * readLine (FILE * file)
  5. {
  6. size_t len = 0;
  7. int c = 0, i = 0;
  8. long pos = ftell(file);
  9. char * out = 0;
  10.  
  11. // read the whole line
  12. do { c = fgetc(file); len++; }
  13. while (c!='\0' && c!='\n' && c!=EOF);
  14.  
  15. // if the cursor didn't move return NULL
  16. if (pos == ftell(file) && c == EOF) return 0;
  17.  
  18. // allocate required memory
  19. out = (char*)malloc(len+1);
  20.  
  21. // rewind cursor to beginning of line
  22. fseek (file, pos, SEEK_SET);
  23.  
  24. // copy the line
  25. do { out[i++] = fgetc(file); }
  26. while (c!='\0' && c!='\n' && c!=EOF);
  27.  
  28. // make sure there's \0 at the end
  29. out[i] = '\0';
  30.  
  31. return out;
  32. }
  33.  
  34. int main (void)
  35. {
  36. // FILE * file = fopen("test.txt", "r");
  37. char * line = readLine(stdin);
  38.  
  39. while(line)
  40. {
  41. printf(line); // print current line
  42. free(line); // free allocated memory
  43. line = readLine(stdin); // recur
  44. }
  45.  
  46. return 0;
  47. }
Success #stdin #stdout 0s 2248KB
stdin
This is the first line.
The second line follows,
and thus the last!
stdout
This is the first line.
The second line follows,
and thus the last!