1

it is always printing an extra character at the end. here is the code:

#include <stdio.h>

int main ()
{
    char bit;
    FILE *fp_read,*fp_write;
    fp_read = fopen("test.txt","r");

    if(fp_read==NULL) {
        printf("Error!! Unable to open the file!!");
        return 1;
    }
    while(!feof(fp_read)) {
        fscanf(fp_read,"%c",&bit);
        printf("%c",bit);
    }
    fclose(fp_read);

    return 0;
}

if test.txt contains 010101 it prints 0101011 . if 00110 it prints 001100. if it contains abc it prints abcc . that means it always repeats the last character.

What is the problem ? can anybody explain ?

Ebrahim Khalilullah
  • 556
  • 1
  • 6
  • 10
  • 2
    You need to read about [why it is wrong to use `feof()` in a file loop](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). – ad absurdum May 13 '17 at 14:05
  • I cannot reproduce the problem on linux. Can you give extra info on the env? – Riccardo Bonafede May 13 '17 at 14:06
  • create a file: test.txt in the same directory and write something in test.txt. – Ebrahim Khalilullah May 13 '17 at 14:09
  • I would expect that this is from using `feof()` incorrectly. If the last character in the text file is `1`, then after it is read, the end-of-file indicator is not yet set, so the loop executes again, and `fscanf()` fails, so `bit` remains unchanged. Then the loop exits. On my system, `\n` is the last character of a text file, so that is what is duplicated. Read the link I provided above in the comments. – ad absurdum May 13 '17 at 14:58

1 Answers1

0

I am not able to reproduce the error.

Refer to David Bowling's first comment in the original post for a neat explanation.

The cppreference page for feof has a shorter version.

The eof function only reports the stream state as reported by the most recent I/O operation, it does not examine the associated data source. For example, if the most recent I/O was a fgetc, which returned the last byte of a file, feof returns zero. The next fgetc fails and changes the stream state to end-of-file. Only then feof returns non-zero. In typical usage, input stream processing stops on any error; feof and ferror are then used to distinguish between different error conditions.

This means that the use of feof in the while loop may not be appropriate. The last character from the file may be junk and will be different in different systems.

Try doing this instead.

while(fscanf(fp_read,"%c",&bit) != EOF) {        
    printf("%c",bit);
}
XOR
  • 314
  • 5
  • 11
  • While it is possible to use `feof()` to control a file loop, most questions here at least don't seem to do it correctly. Certainly OP has used `feof()` incorrectly here; see my comments under the original post. – ad absurdum May 13 '17 at 15:12
  • 1
    Oh yes. That's a very neat explanation. It very well explains the logic behind the text I've quoted. Let me add it to my answer as well. – XOR May 13 '17 at 15:52