1

I wrote a c program which read from a input file and then print each line to the standard output but it don't print the last line of the file!

int main() {

   FILE *rf = fopen("input_text.txt", "r");


   char c;

   if (rf) {
      while ((c = getc(rf)) != EOF) {
          putchar(c);
      }
      fclose(rf);
   }

  return 0;
}

How can i fix this issue? Thanks in Advance!

Naim Rajiv
  • 3,324
  • 2
  • 17
  • 23
  • 3
    try `int c;` instead of `char c;` and `fclose(rf); fflush(stdout);` – BLUEPIXY Nov 19 '15 at 08:27
  • Possible duplicate of [getch and putchar not working without return](http://stackoverflow.com/questions/10256477/getch-and-putchar-not-working-without-return) – Basilevs Nov 19 '15 at 08:28

1 Answers1

2

You likely need to flush the output stream because it is being buffered. Add a call to fflush(stdout); just before fclose:

int main() {

   FILE *rf = fopen("input_text.txt", "r");


   int c;

   if (rf) {
      while ((c = getc(rf)) != EOF) {
          putchar(c);
      }
      fflush(stdout);
      fclose(rf);
   }

  return 0;
}
EkcenierK
  • 1,429
  • 1
  • 19
  • 34
  • 1
    `getc` return type is `int` like `int getc(FILE *stream)` you should change `char c` to `int c`, if not, you will need to cast `getc` `while ((c = (char)getc(rf)) != EOF)` because of the conversion type. – Michi Nov 19 '15 at 09:54