After saving data to files, your C programs need to be able to read that data back into memory. Reading files is a fundamental task, whether you are parsing a configuration file, loading a saved game, or processing a massive dataset.
In this lesson, we will cover the standard C functions used to read text from files: fgets(), fscanf(), and fgetc().
fgets()The fgets() function is the most robust and secure way to read text files line by line. It reads a string from a file until it encounters a newline character (\n), the end of the file (EOF), or it reaches a specified maximum character limit.
fgets(buffer, max_length, file_pointer);
buffer: A character array (string) where the read text will be stored.max_length: The maximum number of characters to read (usually the size of the buffer). This prevents buffer overflow vulnerabilities!file_pointer: The pointer to the open file.#include <stdio.h>int main() { FILE *fptr = fopen("data.txt", "r"); // "r" mode for Reading char buffer[255]; // Array to hold each line if (fptr == NULL) { printf("File not found!\n"); return 1; } // fgets returns NULL when it reaches the End of File (EOF) while (fgets(buffer, sizeof(buffer), fptr) != NULL) { printf("%s", buffer); } fclose(fptr); return 0; }
fscanf()If your file contains structured data (like a list of numbers or specific columns of text), fscanf() is incredibly useful. It works exactly like scanf(), but reads from a file instead of the user's keyboard.
Suppose we have a file scores.txt that looks like this:
> Alice 95
> Bob 82
> Charlie 88
#include <stdio.h>int main() { FILE *fptr = fopen("scores.txt", "r"); char name[50]; int score; if (fptr == NULL) { printf("Error opening file.\n"); return 1; } // fscanf returns the number of items successfully read. // It returns EOF when it reaches the end of the file. while (fscanf(fptr, "%s %d", name, &score) != EOF) { printf("Student: %s | Score: %d\n", name, score); } fclose(fptr); return 0; }
Warning: fscanf() can be tricky if the file formatting isn't exactly what it expects. For complex parsing, reading the line with fgets() and then using sscanf() on the string is often safer.
fgetc()The fgetc() function reads a single character from the file. It returns the ASCII integer value of the character, or the special macro EOF if it reaches the end of the file.
#include <stdio.h>int main() { FILE *fptr = fopen("data.txt", "r"); int ch; // Declare as int to properly check for EOF if (fptr != NULL) { while ((ch = fgetc(fptr)) != EOF) { printf("%c", ch); } fclose(fptr); } return 0; }
Why is fgets() considered safer than older functions like gets() or basic fscanf() for reading strings?