-
Check for EOF
How can I read info from a file and end when the file contains no more info?
I am currently using a '!' (inside the file) on its own to signify the end of the file but this is causing later problems.
I have a vague idea I need to use 'EOF' but I have no idea how to check for this... any help would be great... thanks in advance
-
check this out
well junior friend I hope a while loop would work fine for you...
try something like this...
...
...
}while (!eof(fpr));
where fpr is the file handler opened like
FILE *fpr= fopen(filename, attributes);
tell me if it doesn't.. I have been away from C since very long..
i will double check if it doesn't
right here at
[email protected]
-
Firstly... thanks for your solution...
Secondly... I feel I must apologise...
I have the most frustrating habit of tackling a problem 'till my hands bleed.... then, in ernest, I post my puzzler to this board... then, through some divine intervention, I figure it out on my own within minutes of returning to it...
Most upsetting...
P.S. I used feof instead of eof... are they interchangeable?
-
> I used feof instead of eof... are they interchangeable?
No.
EOF is a status return which you get from various file reading functions (like fgetc). feof() is a function.
If you solved your problem using feof() and not EOF, then you've almost certainly got it wrong. The problem being that feof() will only return true AFTER some other file reading operation (eg fgetc) has returned EOF. If you didn't detect this, then you processed some bogus data.
-
hmmm... it looks like eof() is also a function looking at Zuwayer's solution... albeit one I can't find anywhere.
I realise that EOF is a 'result' but I don't have enough experience to say that eof() isn't a function that looks for that result.
My problem now is that my program works perfectly, despite being wrong ::confused:
This is a small section of the code...
Code:
while (i<no_of_words && feof(input) == 0) {
fgets(temp, 80, input);
len=strlen(temp);
list[i]=(char *)malloc(len);
strcpy(list[i], temp);
i++;
}
So there is a fget* function in there... could that be why it works even though I can't see how feof() would be able to access a result from fgets()?
-
Basically the best way I can think of to put this to you is..
Code:
#include <stdio.h>
int main (void)
{
FILE *fp;
char ch;
if((fp = fopen("filename.txt", "rt+"))==NULL) {
printf("Error opening file for mode");
exit(1);
}
while((ch =fgetc(fp)) !=EOF)
putchar(ch);
/*will print file character by character till end of file*/
fclose(fp)
}
No doubt if I am wrong well hear about it, LOL...
-
> fgets(temp, 80, input);
> len=strlen(temp);
fgets returns NULL when it hits the end of file, and leaves the buffer unmodified.
If you look carefully, you may find that the last line in the file is counted twice.