Introduction
In C programming, working with files is an essential skill. Files are a way to store data persistently, and often we need to read data from files in our programs. This can be done using C’s standard library functions.
In this example, we will learn how to write a program that reads and displays the contents of a text file. The program will open a file in read mode, read its contents, and then display it on the screen.
Objective
The objective of this program is to demonstrate how to use basic file handling functions in C, such as fopen()
, fgetc()
, and fclose()
, to read the contents of a file and print it to the console.
Program Code
#include int main() { FILE *file; char ch; // Open the file in read mode file = fopen("example.txt", "r"); // Check if file opened successfully if (file == NULL) { printf("Error! Could not open file.\n"); return 1; // Exit with error code } // Read and display the contents of the file printf("Contents of the file are:\n"); while ((ch = fgetc(file)) != EOF) { putchar(ch); } // Close the file after reading fclose(file); return 0; }
Explanation of the Program
This C program works as follows:
FILE *file;
declares a pointer to a file structure.fopen("example.txt", "r");
attempts to open the file namedexample.txt
in read mode.- If the file is successfully opened, the program enters a loop where it reads one character at a time using
fgetc()
and prints it usingputchar()
until it reaches the end of the file (EOF). - Finally, the file is closed using
fclose(file);
to release system resources.
How to Run the Program
- Save the program in a file, say
readfile.c
. - Ensure you have a file named
example.txt
in the same directory or update the file path in the program. - Compile the program using a C compiler, e.g., using GCC:
gcc readfile.c -o readfile
. - Run the program:
./readfile
. - The contents of the
example.txt
file will be displayed in the terminal.