开发者

feof, doesn't seem to work - text files

I'm reading lines from a text file using fgets();

I have a loop with: while(!feof(fp))

The thing is, the program keeps entering the loop even after I've reached and read the last line, and in debug the file ptr shows only dots and not a string of data.

How can I get it to know I've reached the end and not enter the loop again?

        while (!feof(fp)) {
            if (strcmp(data2->ID ,data1->ID)<0) {

                fseek(fp, backTo, SEEK_SET);
                fprintf( fp, "%s",lin2);
                fprintf( fp, "%s",lin1);

                flag = 1;
            } 
            else 
            {
                strcpy(data1->ID,data2->ID);
                st开发者_如何学Crcpy(data1->name,data2->name);
                data1->price=data2->price;

            }

            if(fgets(line2, sizeof(line2),fp)!=NULL)
            {
                itemSize2=strlen(line2)+1;
                strcpy(data2->ID,strtok (line2,","));
            }

        }

There are only 2 lines in the text file, I'm using fseek and going to the begining of the file then I use fprintf twice and write on those lines, after that I should reach the EOF


Do you mean it enters the loop once?

feof(fp) returns true if the program has attempted to read beyond the end of file, not when it's read up to it. The system doesn't necessarily know if there's more of a file (it may be dynamically generated, stdin being the canonical example), but does know if it hit an end of file.

You need to test feof(fp) after each fgets(fp), or test to see how many characters were returned by fgets(fp), or do a one-character get and unget.


Well I use this custom function....

BOOL    CheckFileEnd(FILE *fp)
{
    BOOL res;
    long currentOffset = ftell(fp);

    fseek(fp, 0, SEEK_END);

    if(currentOffset >= ftell(fp))
        res = TRUE;
    else
        res = FALSE;

    fseek(fp, currentOffset, SEEK_SET);

    return res;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜