← The C Language Lesson 37 of 77 · 10 XP

Reading files

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

Three ways to read a text file:

int c = fgetc(f);                       // by character; EOF at the end

char line[256];
while (fgets(line, sizeof line, f))     // by line; NULL at the end
    printf("%s", line);                 // the '\n' stays inside line!

int x;
while (fscanf(f, "%d", &x) == 1)        // by a template
    sum += x;

fgets reads no more than size - 1 characters and always adds a '\0', so the buffer won't overflow. It keeps the line break '\n'. You can remove it like this: line[strcspn(line, "\n")] = '\0';.

Moving around a file:

fseek(f, 0, SEEK_END);    // to the end
long size = ftell(f);     // the current position = the size of the file
rewind(f);                // back to the beginning

feof(f) tells you that reading has already hit the end, not that the next read will. That's why while (!feof(f)) is a classic mistake: the last line gets processed twice. Check the result of the reading function itself.

Task. The preparation code has already written the input to the file notes.txt. Read the file line by line with fgets and print the number of lines and the number of characters (not counting '\n'), separated by a space.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.