Lesson 85 +10 XP

Reading Files

Reading Files

Files come back with fgets, one line at a time.

Reading line by line

#include <stdio.h>

int main() {
    FILE *file = fopen("file.txt", "r");
    if (file == NULL) {
        printf("Unable to open file\n");
        return 1;
    }
    char line[100];
    while (fgets(line, sizeof(line), file) != NULL) {
        printf("%s", line);
    }
    fclose(file);
    return 0;
}

Why is line a char array?

fgets needs a buffer to store the line it reads.

fgets returns NULL at the end

The loop condition continues until the file ends.

Reading single characters with fgetc

int ch = fgetc(file);   // next character
printf("%c", ch);

TL;DR

  • fgets(buffer, size, file) reads one line.
  • The while loop + fgets reads the whole file.
  • fgets returns NULL at end of file.
  • Open with "r" for reading.