-
File Management in C
The question:Why do i have to write if(c!=EOF) statement again in do-while block in the following code?
The thing is that if i don't write the if(c!=EOF)again in the block,it outputs the last word again in the end.Can you tell me why that is happening?
Code:
#include<stdio.h>
main()
{
FILE*pt;
char array[100];
int c;
pt=fopen("text.txt","r");
if(pt==NULL) printf("the file doesn't exist");
else {
do {
c=fscanf(pt,"%s",array);
if(c!=EOF)
printf("%s",array);
} while(c!=EOF);
}
fclose(pt);
}
-
Because you're not using EOF consistent with the way it actually works.
Cprogramming.com FAQ > Why it's bad to use feof() to control a loop
Checking for EOF works exactly the same way as feof() (that is to say: it doesn't).
-
I didn't understand you.English is not my native langauge.So can you be clear?
-
Read the link he has provided.
-
Your question is "why do I need to check if I've reached the end of the file before I go off assuming I haven't?"
Here's a similar algorithm for walking through a doorway:
1. Approach the door
2. Walk through the door
3. Check whether the door is open
Hmm...
-
What does fscanf function return here?
You are saying is it because of do-while statement?
First do then check?
I tried with normal While.It still has that problem.
-
Why do you keep refusing to read the material provided to you? The answers you seek are explicit in there.