Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

while(!feof(file)) reading extra line

Tags:

c

file-io

Im having an issue reading in lines from a file. Basically my code is reading in one extra line than it should with all variables being '0'i.e.

If my file is:

0, 0, 3, 64, 0, 0, 0, 0
2, 0, 6, 64, 0, 0, 0, 0
4, 0, 4, 64, 0, 0, 0, 0
6, 0, 5, 64, 0, 0, 0, 0
8, 0, 2, 64, 0, 0, 0, 0

it will read in:

Object 1:  0, 0, 3, 64, 0, 0, 0, 0
Object 2:  2, 0, 6, 64, 0, 0, 0, 0
Object 3:  4, 0, 4, 64, 0, 0, 0, 0
Object 4:  6, 0, 5, 64, 0, 0, 0, 0
Object 5:  8, 0, 2, 64, 0, 0, 0, 0
Object 6:  0, 0, 0,  0, 0, 0, 0, 0

Here is my read algorithm:

while (!feof(pfile)) { 

        PcbPtr p = createnullPcb();
        fscanf(pfile, "%d,%d,%d,%d,%d,%d,%d,%d", &p->arrivaltime, &p->priority, &p->remainingcputime, 
        &p->memalloc, &p->pr,  &p->sc, &p->mo, &p->cd);
        char cwd[1024];
        char *tmp = getcwd(cwd, sizeof(cwd));
        strcat(tmp, "/process");
        p->args[0] = tmp;
        p->args[1] = NULL;

        if (!headi) {
            headi = p;
        } 
        else {
            enqPcb(&headi, p);
        }

    }

Why is this happening? Thanks for any help!

like image 250
Milk Avatar asked Apr 09 '26 02:04

Milk


1 Answers

What's happening is that feof returns true when there was an attempt to read past the end. When you are at the end of your file, but haven't tried to read anything else yet, feof will return false.

In simple words: feof does not stand for is at the end of the file, but for has attempted to access past the end of the file.

Note that when you are at the end of the file and try to read that extra line, fscanf will fail. You could check its return value to see if it was able to read anything.

like image 127
K-ballo Avatar answered Apr 12 '26 13:04

K-ballo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!