Opening and reading files line-by-line
What you'll learn: How to safely open a text file and process its contents one line at a time using fopen and fgets.
The Handshake: Opening a File
Before your program can read a file, it needs to ask the operating system for permission. Think of this like checking out a book from a library. You use the fopen() function, which requires two things: the name of the file and the "mode" (like "r" for reading).
If the file exists, fopen hands you a pointer to a FILE structure—essentially a bookmark that keeps track of where you are in the text. If something goes wrong (like the file being missing), it returns NULL. You must always check for NULL before proceeding, or your program will crash.
Reading Line-by-Line
To build a command-line utility, you rarely want to dump the entire file into memory at once. Instead, you read it line-by-line using fgets(). This function acts like a vacuum: it sucks up text until it hits a newline character (\n) or reaches a size limit you set.
We typically wrap fgets() in a while loop. The loop continues as long as fgets successfully finds more text. Once it hits the end of the file, it returns NULL, and the loop gracefully ends.
Putting it Together
Here is the standard pattern for reading a file safely:
#include <stdio.h>
int main() {
// 1. Open the file for reading ("r")
FILE *filePtr = fopen("example.txt", "r");
// 2. Safety check: Did the file actually open?
if (filePtr == NULL) {
printf("Error: Could not open file.\n");
return 1;
}
char buffer[100]; // A temporary container for each line
// 3. Read line-by-line until the end of the file
while (fgets(buffer, 100, filePtr) != NULL) {
printf("Line content: %s", buffer);
}
// 4. Close the file to free up system resources
fclose(filePtr);
return 0;
}
The Cleanup
Just as you must return a library book, you must close your file using fclose(). This tells the operating system that you are done, preventing memory leaks and ensuring other programs can access the file if needed.
Key takeaway
Always verify that your file pointer isn't NULL before using fgets() to loop through the text.