In this article, we will write a C program to print the content of a file.
The program takes the name or path of the file as input from the user, reads the file from start to end, and then prints the entire content of the file on the output window.
Sample Input:
Enter the file name or file path: data.txt
Sample Output:
File content is as follows: This is a sample text file to understand the workflow of file reading/writing in C programming.
To read the content of a file in C programming, you need two inbuilt functions, the fopen() and fgetc().
The fopen()
function lets you open a file in the specified mode such as read(“r”), write(“w”), etc. whereas the fgetc()
function lets you read each character of the opened file or a string one by one.
Here is the syntax of the fopen()
function:
FILE *fopen(const char *filename, const char *mode);
To read the content of a file, we can pass the name or path of the file as a first parameter to the fopen()
function and the mode in which the file should open as a second parameter. As we only want to read the content of the file, therefore, we will pass the mode as “r” which denotes the read-only mode.
If the fopen()
successfully opens the specified file, it will return a FILE pointer, which will by default point to the beginning of the file. If not, it returns a NULL pointer.
We can then pass the FILE
pointer to the fgetc()
function, which will initially return the first character of the file.
We will continue calling the fgetc()
function which will one by one give us the next characters of the file until it reaches the end of the file(EOF). Once the end of the file is reached, we will stop calling the fgetc()
function and break the loop.
See implementation in the following program:
// C program to print the // content of a given file #include <stdio.h> int main(){ char filename[100], ch; printf("Enter the file name or file path: "); scanf("%s", &filename); // Try to open the file in read mode FILE *fptr = fopen(filename, "r"); // Check if file pointer *fptr is NULL if(fptr == NULL){ printf("File does not exist or cannot be opened."); return 1; } // Call the fgetc() function ch = fgetc(fptr); printf("File content is as follows: \n"); // Continue calling fgetc() until EOF reached while(ch != EOF){ printf("%c", ch); ch = fgetc(fptr); } // Close the file at the end fclose(fptr); return 0; }
Output:
Enter the file name or file path: data.txt File content is as follows: This is a sample text file to understand the workflow of file reading/writing in C programming.
Note: It is important to close the file at the end once you finish performing all the tasks on it. You can use the fclose()
function for this purpose.
This is important because, on some systems, a file may be locked while it’s open by a program. Closing the file releases this lock, allowing other programs or processes to access the file without contention.
I hope you liked this article. Thanks for reading!