In this post, we are going to see how to write a simple C program to read a text file and print its content. We are going to use C pointers to read the file. So without wasting time let’s see the program.
Make sure you have the text file (myfile.txt) in the same place where you are going to execute the below C program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
#include <stdio.h> int main() { //declare variables FILE *filePointer; char character; //set your filename here char fileName[] = "myfile.txt"; printf("Reading the file...\n"); printf("\n"); //if the file does not exist return error if ((filePointer = fopen(fileName, "r")) == NULL) { perror(fileName); return 1; } printf("%s contains: \n", fileName); //red the file and print the content while (1) { character = fgetc(filePointer); if (character == EOF) { break; } printf("%c", character); } fclose(filePointer); return 0; } |
The above code is self-explanatory. I have updated the comments inline. Just read them to understand it. You can set your file name in this variable called “fileName“.
An example output would be,
Scenario 1 – (if the file does not exist):
1 2 3 4 5 6 7 |
Reading the file... myfiles.txt: No such file or directory -------------------------------- Process exited after 0.1652 seconds with return value 1 Press any key to continue . . . |
Scenario 2 – (If the file exist):
1 2 3 4 5 6 7 8 9 |
Reading the file... myfile.txt contains: agurchand test what? -------------------------------- Process exited after 0.1668 seconds with return value 0 Press any key to continue . . . |
I hope this program clears your doubts on how to read a text file using C programming and display its content.