Archived

This topic is now archived and is closed to further replies.

Traverse a Text File using C

This topic is 5014 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have a series of records in a text file and I want to find a particular record. I want to read the file record by record until i find the correct record. I know you can use a while loop and an if statement together to get the correct record but I don''t know what loop guard to put in place. This is what my code looks like at the mo. According to our lecturer you must use fsetpos() and fgetpos() with text files. FILE *fp; while (fp != EOF){ // This LOOP GUARD is WRONG - NEED HELP fread(&inCandidate,sizeof(inCandidate),1,fp); if (searchID == inCandidate.ID) fgetpos(); } fsetpos(); printf("The Record is: ");

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
The EOF flag is only set AFTER you attempt a read on the file.

You might try:

FILE *fp;

fp = fopen("somefile", "rt";
if (!fp) throw "biatch";

fread(&inCandidate,sizeof(inCandidate),1,fp);
while (!feof(fp))
{
// Process here

// get next...
fread(&inCandidate,sizeof(inCandidate),1,fp);
}

Share this post


Link to post
Share on other sites
fread returns the number of record successfully read. You could use this;

FILE *fp;

fp = fopen("somefile", "rt";
if (!fp) throw "biatch";

while (fread(&inCandidate,sizeof(inCandidate),1,fp)==1)
{
// Process here

}


For binary files only of course.

[edited by - Kurioes on March 26, 2004 6:04:12 AM]

Share this post


Link to post
Share on other sites
How about using a do...while loop.


FILE *fp;
fp = fopen("somefile", "rt");
do
{
if ( fread(whatever args are reqd...) != nExpectedReturn )
break;
if ( ...found the right record... )
break;
} while ( !feof(in) );


You may need to modify the internals of the loop if you need to use your fgetpos etc.

R

--------------------------------------------------------------------------
There is no point in flaming if you''ve merely poured fuel on your own head

Share this post


Link to post
Share on other sites