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

C Program for File Handling

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

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

FILE *fp;

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


To read the name and roll number of a student, first we have to open the exam.dat file in read mode "r" and check if the file exists or not. If it exists, 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 number 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 does not exist"); } 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; }

Conclusion

File handling in C is a crucial concept for storing and retrieving data efficiently. By using files, programs can save data permanently, read it when needed, and manage large amounts of information. Understanding how to create, read, and close files ensures better data management and program functionality.

C program File

Solve More Problem Like This Click Here :

Javascript code to calculate Factorial Number

Previous Post Next Post