Grove
Grove

Reputation: 21

Why does this program behave like `tail -f`

int main(int argc, char *argv[])
{
    int c = EOF;
    FILE *fp = fopen("./temp.txt", "r");
    assert(fp!=NULL);
    while (1) {
        c = fgetc(fp);
        if (EOF != c) {
            putchar(c);
        }
    }

    return 0;
}

temp.txt is a slowly increasing log file, so this program can read the EOF. After it first encounters EOF, I thought it should stop getting new added data of temp.txt, while it just acts like tail -f temp.txt and continues printing new lines of the file.

Yes, I know there is an infinite loop. The problem is that I thought, when fgetc first encounters EOF, it should do some recording in the struct fp, and the next callings of fgetc should check this and return EOF immediately. Why it continues to read the data on the disks, didn't it reach the end-of-file? Is this the expected behavior?

Upvotes: 2

Views: 195

Answers (5)

Serve Laurijssen
Serve Laurijssen

Reputation: 9733

IMO it would be nicer looking when you do

int c = 0;
while ((c = fgetc(fp)) != EOF)
{
    putchar(c);
}

Upvotes: 0

pradipta
pradipta

Reputation: 1744

int main(int argc, char *argv[])
{
    int c = EOF;
    FILE *fp = fopen("./temp.txt", "r");
    assert(fp!=NULL);
    while (1) {
        c = fgetc(fp);
        if (EOF != c) {
            putchar(c);
        }
        else
          break; //this will fix your problem of infinite loop even finding EOF
    }

    return 0;
}

Upvotes: 0

nouney
nouney

Reputation: 4411

int main(int argc, char *argv[])
{
    int c = EOF;
    FILE *fp = fopen("./temp.txt", "r");
    assert(fp!=NULL);
    while (1) { // here
        c = fgetc(fp);
        if (EOF != c) {
            putchar(c);
        }
    }

    return 0;
}

It's because you have an infinite loop which can't be stopped (except with some signals). This program will read temp.txt for the eternity.

Upvotes: 0

Jon Taylor
Jon Taylor

Reputation: 7905

You aren't telling it to leave the while loop when finding an EOF though, you are only saying if you do find a EOF don't do anything with it. You would need to put a conditional break from the loop or have a condition until which the while loop will continue.

Upvotes: 1

newfurniturey
newfurniturey

Reputation: 38436

Quick answer is, there is no break that exits the while loop.

When it reads EOF, it loops back around and holds on c = fgetc(fp);.

If you need it to stop reading when it hits the EOF you can add an else:

while (1) {
    c = fgetc(fp);
    if (EOF != c) {
        putchar(c);
    } else {
        // reached the EOF
        break;
    }
}

Upvotes: 2

Related Questions