C Program: Read a File

In this tutorial, we will write a C program to read and print the contents of a file.

For the purpose of example, let us consider a simple text file.

c program read file

We create the text file, which is to be read. Copy the first stanza of the poem "The Tyger" by William Blake, paste it in a new file and save it as tyger.txt inside your C program directory.

the tyger by william blake
				
				Tyger Tyger, burning bright, 
				In the forests of the night; 
				What immortal hand or eye, 
				Could frame thy fearful symmetry? 
				
			

We will open tyger.txt, read its contents and print the whole stanza into the terminal.

To open tyger.txt, we use the fopen() function, which opens it as per the mode provided to it in the last argument. Here we will be opening the file in the "r" ("read") mode. The fgetc() function returns a single character from the input stream, all the while increasing the position of the file pointer. It returns EOF at the end of the file. The fclose() function closes the file associated with the file pointer.

Here is the C program for reading and printing out the contents of a file.

				
				#include <stdio.h>
				 
				int main() {
				   char c, file[50];
				   FILE *fp;
				 
				   printf("FILENAME: ");
				   scanf("%[^\n]", file);
				 
				   fp = fopen(file, "r"); // 'r' opens the file in read mode
				 
				   printf("READING THE CONTENTS OF THE FILE [ %s ]\n", file);
				 
				   while((c = fgetc(fp)) != EOF) {
				      printf("%c", c);
				   }
				 	
				   printf("\n");

				   fclose(fp);
				   return 0;
				}
				
			

On executing the program, the prompt to enter FILENAME will appear. Enter tyger.txt.

				
					$ ./a.out
					FILENAME: tyger.txt
				
			

The program prints the contents of the entered file as

c program read txt file

Well, .txt files aren't just the only files to be read. You can read and print the contents of a C program file itself. If the above C program is saved as read.c, run the program as

				
					$ ./a.out
					FILENAME: read.c