-
advice on feof()
I've written a program which sorts variable sized records on a binary file
into customer number order. I'm using feof() to terminate my loops, which
works and I get the required results. I'm just wondering if I'm using feof
in the right place and correctly.
The program goes something like this
in main there's this loop
Code:
while(1)
{
open files:
alternate input file and exchange file, read from one, write to the other
read first character from input file /*to determine what type of record*/
if(!feof(input file)
{
read the record into union 'a' /*a union of structures*/
sort_function(...)
}
else
{
close input and exchange files
break;
}
}
in the sort function
Code:
while(1)
{
read next character from input file
if(!feof(input file)
{
read the record into union 'b'
compare customer numbers 'a' & 'b'
write record with highest customer number to exchange file
}
else
break;
}
write record with lowest customer number to sort file
close input and exchange files
I've searched the board for other posts on feof and I get the feeling It's maybe
not a good idea to use it. When I first wrote the program I used the return value of
fread to terminate the loop, but I had read that it returns zero on end of file or error
and you should use feof to determine which.
Hope this isn't too vague. Thanks for any advice you can give.
hobo
-
Well, the best way to do it, is to test the return value of your function that reads the input. If it fails, then either there was an error, or there was nothing left to read (Actually both would be an error).
Here's what I mean:
Code:
if(read the record into union 'a' == TRUE)
{
/*a union of structures*/
sort_function(...)
}
else
{
close input and exchange files
break;
}
-
Thanks for your response, either way it produces the same results, but I can see why testing the return value of the read function is the better way to go.
Thanks again.
hobo