In this tutorial, you'll learn how to read a text file and display its contents on the console using the C programming language. This is the natural companion to Assignment 1 (creating and writing a file). The program opens the file in read mode, reads it line by line with fgets(), and prints each line. It's the foundation for almost every other file-handling program — counting words, searching, sorting, merging, and more.
📝 Problem Statement
Write a program in C to read and display the contents of a text file.
⚙️ How the Program Works
The program follows the standard read lifecycle:
- Ask for the filename (or hard-code it) and store it in a character array.
- Open the file in read mode with
fopen("filename.txt", "r")and check forNULL. - Read line by line using
fgets()into a buffer. The loop ends whenfgetsreturnsNULL(end of file or read error). - Print each line to the console with
printf()orfputs(). - Close the file with
fclose()to release the handle.
💻 Complete C Program
#include <stdio.h>
int main(void)
{
FILE *fp;
char filename[100];
char line[1024];
printf("Enter the filename to read: ");
scanf("%99s", filename);
/* Open the file in read mode */
fp = fopen(filename, "r");
if (fp == NULL)
{
printf("Error: Could not open file '%s'.\n", filename);
return 1;
}
printf("\n--- Contents of %s ---\n\n", filename);
/* Read one line at a time until end of file */
while (fgets(line, sizeof(line), fp) != NULL)
{
printf("%s", line);
}
printf("\n--- End of file ---\n");
fclose(fp);
return 0;
}🖥️ Sample Output
Assume sample.txt contains the following lines:
sample.txt:
Hello, World!This text was written using fprintf.
File handling in C is fun!
Running the program:
--- Contents of sample.txt ---
Hello, World!
This text was written using fprintf.
File handling in C is fun!
--- End of file ---
🔍 Line-by-Line Explanation
| Line / Code | Explanation |
|---|---|
char line[1024]; |
A buffer large enough to hold one line of text. 1024 bytes is enough for typical lines; use a larger buffer if your file has long lines. |
scanf("%99s", filename) |
Reads the filename without spaces. %99s caps the input at 99 characters to avoid a buffer overflow. |
fopen(filename, "r") |
Opens the file for reading. Returns NULL if the file doesn't exist or cannot be read. |
fgets(line, sizeof(line), fp) |
Reads up to sizeof(line) - 1 characters or until a newline, whichever comes first. Returns NULL at end of file. |
printf("%s", line) |
Prints the line. fgets keeps the trailing newline, so %s alone produces correct output. |
fclose(fp) |
Releases the file handle. Always call this when done. |
fgets stops at the newline or when the buffer is nearly full — whichever comes first. If a line is longer than 1023 characters, it will be returned in multiple chunks. The output will still be correct, but each chunk is treated as a separate iteration.
🔁 Other Ways to Read a File
fgets is the most common approach, but C gives you a few other options, each suited to a different task:
| Function | Reads | Best for |
|---|---|---|
fgets() |
One line at a time | Displaying, searching, or processing line-based text |
fgetc() |
One character at a time | Counting characters, converting case, encrypting |
fscanf() |
Formatted tokens (words, numbers) | Reading structured text like CSVs or numeric data |
fread() |
Raw bytes | Binary files (see Assignments 7 and 8) |
Here is the same task using fgetc — one character at a time. It's a bit more verbose but easier to adapt for character-level processing:
#include <stdio.h>
int main(void)
{
FILE *fp;
char filename[100];
int ch;
printf("Enter the filename to read: ");
scanf("%99s", filename);
fp = fopen(filename, "r");
if (fp == NULL)
{
printf("Error: Could not open file.\n");
return 1;
}
/* fgetc returns int (not char) so EOF is distinguishable */
while ((ch = fgetc(fp)) != EOF)
{
putchar(ch);
}
fclose(fp);
return 0;
}
Note the int ch — fgetc returns int, not char, so that EOF (-1) can be distinguished from the byte value 255. Declaring ch as char is a classic bug.
🐛 Common Pitfalls
- Declaring
chaschar: When usingfgetc, always declare the receiving variable asintsoEOFis detected correctly. - Forgetting the
NULLcheck: A missing file causes a crash on the first read. - Buffer too small: If a line exceeds the buffer,
fgetsreturns it in pieces. For very long lines, either enlarge the buffer or usefgetc. - Not closing the file: Skipping
fcloseleaks file descriptors and may leave buffered data unflushed.
💡 Tips & Best Practices
- Use
%99s(or the appropriate width) withscanfto prevent buffer overflows. - If you need the filename to contain spaces, use
fgetsto read it and strip the trailing newline. - Compile with
gcc -Wall -Wextra -std=c11 -gto catch type mismatches and unused variables. - When displaying a file on Windows, note that
fgetsin text mode converts\r\nto\nfor you.