Possible Duplicate:
fgetc does not identify EOF
fgetc, checking EOF
I have created a file and named it “file.txt” in Unix. I tried to read the file content from my C program. I am not able to receive the EOF character. Unix doesn’t store EOF character on file creation? If so what is the alternative way to read the EOF from a Unix created file using C.
Here’s the code sample
int main(){
File *fp;
int nl,c;
nl =0;
fp = fopen("file.txt", "r");
while((c = fgetc(fp)) != EOF){
if (c=='\n')
nl++;
}
return 0;
}
If I explicitly give CTRL + D the EOF is detected even when I use char c.
This can happen if the type of
cischar(andcharis unsigned in your compiler, you can check this by examining the value ofCHAR_MINin ) and notint.The value of
EOFis negative according to the C standard.So, implicitly casting
EOFtounsigned charwill lose the true value ofEOFand the comparison will always fail.UPDATE: There’s a bigger problem that has to be addressed first. In the expression
c = fgetc(fp) != EOF,fgetc(fp) != EOFis evaluated first (to 0 or 1) and then the value is assigned toc. If there’s at least one character in the file,fgetc(fp) != EOFwill evaluate to 0 and the body of thewhileloop will never execute. You need to add parentheses, like so:(c = fgetc(fp)) != EOF.