Write a C program to read name and roll from a file named exam.dat and display them.

 A file represents a sequence of bytes on the disk where a group of related data is stored. You can say, File is a storage area for data. It is ready made structure.

To write a C program, in order to create a file or read data from a file, we have to establish a buffer area. That is created using following syntax :

                FILE *fp;

Where fp is a pointer that points a buffer area and FILE is written in uppercase. Here, fp indicates the begining of the buffer area. 

C program File


To read name and roll of a student, first we have to open the exam.dat  file in read mode that is "r" and check if the file exists or not. If it exits, we will retrieve the content from the file using fscanf and display it using printf.

Here is the program.

#include<stdio.h>

#include<stdlib.h>

int main()

{

char name[20];   //It will copy the name from the file

int roll;   //It will copy the roll no. from the file

FILE *fp;     //fp denotes the starting of buffer area.

fp=fopen("exam.dat","r");    //fp will store the exam.dat file and opens in read mode

if(fp==NULL)   //if there is no file

{

printf("File doesnot exits");

}

else

{

fscanf(fp,"%s,%d",name,&roll);     //copy the name and roll

printf("Name=%s, Roll No.=%d",name,roll);   //display whatever it gets from the file

}

fclose(fp);  //it will close the buffer area

return 0;

}


Solve More Problem Like This Click Here :

Javascript code to calculate Factorial Number

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.