“C File Program to Save Records” is a file handling program in C programming language. This program will open a binary file and save the records of students in it. If the file does not exist already, it is created.
It will add one record at a time. After saving first record successfully in a file, it will ask from user to ‘Do you want to add more records – Press y or n=’. If the user enters ‘n’ then program will be terminated. Otherwise the program will ask the user to enter a new record of student.
Similarly after every record entered, it will ask the user again.
We will use the following C statements to accomplish the given task of storing the records of students in a C File in binary format.
Declare a File Pointer
We will use the statement
to declare a file pointer.
We use a library function fopen() to open a file in a specific mode for reading, writing or appending etc.
fptr = fopen(“filename”,”open-mode”);
Ask to user for entering information for Record
If file is opened successfully, the program will ask the user to enter necessary information to record.
Writing a single Record to Binary File
After getting the information from the user, the program will use another library function known as fwrite() to write / store the record in the binary file.
fwrite(&srecord, sizeof(srecord), 1, fptr);
Wish to add more Records? Press y / n ?
After writing the given record into binary file, the program will ask the user to press ‘y’ if he wishes to add more records or press ‘n’ to stop.
Closing a File
We use a standard library function known as fclose() to close the opened binary file
In this way our C program to save records in a binary file, reaches to end.
The source code of the C File program for writing / storing records in a binary file:
1,009 total views, 1 views today