How to Read File Line by Line in C: Simple Guide
To read a file line by line in C, open the file with
fopen, then use fgets in a loop to read each line into a buffer until the end of the file. Always check if the file opened successfully and close it with fclose after reading.Syntax
Here is the basic syntax to read a file line by line in C:
FILE *fp = fopen("filename", "r");opens the file for reading.char buffer[SIZE];declares a buffer to store each line.while (fgets(buffer, SIZE, fp) != NULL)reads each line until the end.fclose(fp);closes the file when done.
c
FILE *fp = fopen("filename.txt", "r"); char buffer[256]; if (fp == NULL) { // handle error } while (fgets(buffer, sizeof(buffer), fp) != NULL) { // process the line stored in buffer } fclose(fp);
Example
This example opens a file named example.txt, reads it line by line, and prints each line to the screen.
c
#include <stdio.h> int main() { FILE *fp = fopen("example.txt", "r"); if (fp == NULL) { printf("Failed to open file.\n"); return 1; } char line[256]; while (fgets(line, sizeof(line), fp) != NULL) { printf("%s", line); } fclose(fp); return 0; }
Output
Hello, this is line one.
This is line two.
And this is line three.
Common Pitfalls
Common mistakes when reading files line by line include:
- Not checking if
fopenreturnsNULL, which means the file failed to open. - Using
fgetswithout a large enough buffer, causing lines to be cut off. - Not handling the newline character that
fgetskeeps at the end of each line. - Forgetting to close the file with
fclose, which can cause resource leaks.
c
// Wrong way: Not checking file open FILE *fp = fopen("file.txt", "r"); char line[10]; while (fgets(line, sizeof(line), fp) != NULL) { printf("%s", line); } // Missing fclose(fp); // Right way: FILE *fp2 = fopen("file.txt", "r"); if (fp2 == NULL) { // handle error } char line2[256]; while (fgets(line2, sizeof(line2), fp2) != NULL) { printf("%s", line2); } fclose(fp2);
Quick Reference
| Function | Purpose |
|---|---|
| fopen(filename, "r") | Open file for reading |
| fgets(buffer, size, file) | Read one line into buffer |
| fclose(file) | Close the opened file |
| NULL check | Verify file opened successfully |
Key Takeaways
Always check if fopen returns NULL before reading the file.
Use fgets in a loop to read each line safely into a buffer.
Choose a buffer size large enough to hold the longest expected line.
Remember to close the file with fclose to free resources.
fgets keeps the newline character; handle it if needed.