Back to Blog

C in 100 Seconds: File I/O Reading

Daryl WongDaryl Wong

Video: C in 100 Seconds: File I/O Reading — fopen, fgets, fgetc | Episode 35 by Taught by Celeste AI - AI Coding Coach

Watch full page →

File I/O — Reading

Reading files in C follows a simple pattern: open, read, close. All the functions you need are in stdio.h.

fopen — Open a File

FILE *f = fopen("/tmp/sample.txt", "r");
if (f == NULL) {
  printf("Could not open file\n");
  return 1;
}

Pass the file path and the mode — "r" for reading. Always check the return value for NULL — the file might not exist or you might lack permissions.

fgets — Read Line by Line

char line[256];
while (fgets(line, sizeof(line), f) != NULL) {
  printf("%s", line);
}

fgets reads one line at a time into a buffer. It stops at the newline character or when the buffer is full. When it returns NULL, you have reached the end of the file.

fgetc — Read Character by Character

int ch;
while ((ch = fgetc(f)) != EOF) {
  chars++;
}

fgetc returns an int, not a char, because EOF is a special value that does not fit in a char. Use it when you need byte-level control.

fclose — Always Close

fclose(f);

Open file handles leak resources. Always close when you are done reading.

Student Code

Try it yourself: episode35/readfile.c