2

I'm trying to read each character from a file and print it to the screen using getc and putc alone. Here's my code,

FILE *fp = fopen("new.txt","r+");
rewind(fp);
while( feof(fp) == 0 )
{
      putc( getc(fp) , stdout);
}

When ever I execute this, it runs into an infinite loop. I can't understand how this happens when the file is only a few lines long.

Newbie.

kesari
  • 536
  • 1
  • 6
  • 16
  • 1
    You might to want to read a [reference on `fopen`](http://en.cppreference.com/w/c/io/fopen), as that code shouldn't even compile. – Some programmer dude Mar 11 '14 at 19:56
  • "while feof" is wrong. See http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong – Thomas Padron-McCarthy Mar 11 '14 at 19:57
  • @JoachimPileborg Why link to cppreference ? – cnicutar Mar 11 '14 at 19:57
  • Please copy and paste exactly the code you compiled and tried. The code in your question, with r+, does not even compile. Also, show a complete example, not just the part that you think is the problem. – Thomas Padron-McCarthy Mar 11 '14 at 19:58
  • @cnicutar They have both a [C++ reference](http://en.cppreference.com/w/cpp) *and* a [C reference](http://en.cppreference.com/w/c). – Some programmer dude Mar 11 '14 at 20:00
  • @ThomasPadron-McCarthy while you're right of course, surely you're aware that he's opening the file with mode `"r+"`... if he provided the exact code in this case, you wouldn't have any new details and you already have enough information in what you've looked at to understand the cause of the problem. – mah Mar 11 '14 at 20:00
  • @mah: Yes, I agree that it is very likely that he is opening the file with "r+", But I _don't_ understand the cause of the problem. (The feof thing doesn't cause an infinite loop.) Since the code in the question has _one_ obvious error that shows that it can't be the actual code he runs, isn't it reasonable to suspect that there might be other, more crucial, differences? – Thomas Padron-McCarthy Mar 11 '14 at 20:08

2 Answers2

7

Looping while feof returns zero is almost never correct.

Instead you might want to read from the input and check that the input function didn't fail in one expression:

int ch;
while ((ch = getc(fp)) != EOF)
    putc(ch, stdout);

This reads a character using getc, checks that the reading was successful by comparing the character against EOF, and if it's not EOF then continue the loop.

Besides, there's no use in calling rewind immediately after opening the file, the file is already "rewound".

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

use the following program for your answer.use fgetc() to get the character from file and use printf() function to print the character to screen.

#include<stdio.h>
#include<conio.h>
main()
{
    FILE *fp;
    char c;
    clrscr();
    fp=fopen("new.txt","r+");
    c=fgetc(fp);
    while(c!=EOF)
    {
        printf("%c",c);
        c=fgetc(fp);
    }
    getch();
}
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356