errorhandler
errorhandler

Reputation: 1767

Reading a file is skipping lines in C

I have a file named todo.txt and I have a function that will list every line in the file:

void list() {
    FILE *todoFile;
    todoFile = fopen("./todo.txt", "r");
    char line[4096];
    int len;

    if (todoFile != NULL) {
        while (fgets(line, sizeof line, todoFile)) {
            len = strlen(line);
            if (len && (line[len - 1] != '\n')) {
                printf("%s", line);
            }
            printf("%s", line);
            fclose(todoFile);
        }
    } else {
        printf("ERROR");
    }

}

todo.txt contents is:

* foo! 
* hello 
* FP!

but when I use the list() function only the first line is printed:

* foo!

Any ideas?

Upvotes: 0

Views: 361

Answers (2)

AbdullahC
AbdullahC

Reputation: 6730

You need to close your file after you're done with the reading in the while loop.

void list() {
    FILE *todoFile;
    todoFile = fopen("./todo.txt", "r");
    char line[4096];

    if (todoFile != NULL) {
        while (fgets(line, sizeof line, todoFile)) {
            printf("%s", line);
        }
        fclose(todoFile);
    } else {
        printf("ERROR");
    }
}

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798526

You can't call fgets() on a closed file.

Upvotes: 3

Related Questions