codescracker


c

C Program to Read and Display File



« Previous Program Next Program »


Read and Display File in C

To read and display file's content in C programming, you have to first open that file by using fopen() function, now start reading file's content character by character and display its content character by character at the time of reading

C Programming Code to Read and Display File's Content

In the below C program, we have created a file named file.txt with four line of text. Now let's see the below program to know how to read the file and display its content on the screen

Following C program ask to the user to enter the file name like (file.txt) to read its content and display the content of this file on the screen:

/* C Program - Read and Display File's Content */
		
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
	clrscr();
	FILE *fp;
	char s[100], fname[20];
	printf("Enter file name to read and display its content (like file.txt) : ");
	scanf("%s",fname);
	fp=fopen(fname, "r");
	if(fp==NULL)
	{
		printf("Error in opening file..!!");
		getch();
		exit(0);
	}
	while(fgets(s, 99, fp)!=NULL)
	{
		printf("%s",s);
	}
	printf("\n");
	fclose(fp);
	getch();
}

When the above c program is compile and executed, it will produce the following result:

c program read and display file content

Here, the above C program ask to the user to enter file name (like file.txt) to read all the content present in the file and display all its content on the screen

Same Program in Other Programming Language

You may also like same program in other programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test