C Read Files

C Read Files: Extracting Data

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().


1. Reading Line by Line with 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.

Syntax:

fgets(buffer, max_length, file_pointer);

Example: Reading a whole file

fgets() Example

#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; }

*Note: `fgets()` includes the newline character (`\n`) in the buffer if it reads one.*

2. Reading Formatted Data with 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.

Example: Reading structured data

Suppose we have a file scores.txt that looks like this: > Alice 95 > Bob 82 > Charlie 88

fscanf() Example

#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.


3. Reading Character by Character with 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.

fgetc() Example

#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; }


Exercise

?

Why is fgets() considered safer than older functions like gets() or basic fscanf() for reading strings?