jcrshankar
jcrshankar

Reputation: 41

End of file reading in c

My program is reading the last line of data from an infile twice. When I execute the program, the last line of data is being printed twice. Please Help me! Here is the code,

while ( !feof ( in ) ) {
//fread();
}

I hope this happens because of feof functionality.

I don't want to use fgets or getline. Is there is any other way? Please direct me.

Thanks to all who responded me! I got the solution for this! I did with fgetc and unfgetc in side the do loop.

Here is the code:

int ch;
ch=fgetc(fp);
do
{
ungetc(ch,fp);
//fread();

ch=fgetc(fp);
} while( (ch = fgetc(fp)) != EOF && ch != '\n' );

Upvotes: 4

Views: 2973

Answers (2)

kiner_shah
kiner_shah

Reputation: 4681

Try this! Use fscanf for input operations.

while(fscanf(stdin, "%s", in) != EOF) {
//your code
}

Upvotes: 1

Byron Whitlock
Byron Whitlock

Reputation: 53921

You have to use a do... while loop to use feof() properly in c.

if (!feof()) // in case the file is zero length.
{
  do
  {
       //whatever....          
  } while(!feof())
}

Upvotes: 1

Related Questions