C++ – Outputting from file one line at a time

c++file-io

I'm trying to output text from a file one line at a time. I'm currently hardcoding it and I have this so far:

int main(int argc, char *argv[])
{
    int x;
    int k;
    int limit = 5;
    FILE *file;

    file = fopen("C:\\Documents and Settings\\jon\\My Documents\\Visual Studio 2008\\Projects\\Project1\\Assignment8_2\\Debug\\TestFile1.txt", "r");
    if (file == NULL) {
        perror("Error");
    }

    for (k = 1; k <= limit; k++) {
        while ((x = fgetc(file)) != '\n') {
            printf("%c", x);
        }
    }
    fclose(file);
}

I was wondering where in the code above, if at all, I can check for EOF. I assume I need to do that, but not sure why. Still learning…. Thanks!

Best Solution

If you can bound the maximum length of a line, fgets may be a better way to read each line; but since you mention C++, you might consider using, instead, getline (caveat: fgets also put the \n in the buffer it fills, getline doesn't). Both make easy to check for end of file (fgets returns NULL on eof, getline sets the eofbit on its istream argument, which it also returns).