errorhandler
errorhandler

Reputation: 1767

looping over each line of a file in C

I'm wondering how you can loop over each line of a file heres the code I have so far:

FILE *todoFile;
todoFile = fopen("./todo.txt", "r");

if (todoFile != NULL) {

} else {
    printf("ERROR");
}

Upvotes: 2

Views: 11192

Answers (1)

pmg
pmg

Reputation: 108986

The idiomatic way to read a file line-by-line until it ends is

    /* assume line is a char array */
    while (fgets(line, sizeof line, handle)) {
        size_t len = strlen(line);
        if (len && (line[len - 1] != '\n')) {
            /* incomplete line */
        }
        /* possibly remove trailing newline ... and */
        /* deal with line */
    }

Upvotes: 8

Related Questions