We have discussed opening & reading from the file in our previous Article “C Programming – Dealing with files – How to read from a file?“.
Another important buffered function, ‘C’ provides is fwrite function. fwrite function writes to the file. The file should be opened with fopen function call. The syntax of this fwrite function is:
size_t fwrite(const void *ptr, size_t size, size_t ntimes, FILE *fp);
The syntax is same like fread function. fread reads from the file; whereas fwrite writes to the file.
First parameter “
const void *ptr” is points to the address of the data you want to store into the file. Data will be stored as chunks of bytes. Size of the chunk should be mentioned in second argument “
Through third argument “
size_t ntimes“, we need to pass number of times to write the chunks to the file. And the last argument “
FILE *fp“, is the valid file pointer; which gets it from the previous successful call to fopen function.
On success, fwrite function will returns the number of bytes written into the file. There are several reasons this function fails; like, disk is full, no access to write to the file etc.,.
Another interesting function is fseek. fseek function allows to move the file position indicator to a new location. The position of current file position indicator is depends on it’s last I/O operation. This function is useful when you want to read from or write to particular position in the file. The syntax of this function is:
int fseek(FILE *stream, long offset, int origin);
First parameter “
FILE *stream“, is the valid file pointer; usually we will get it from fopen function call. “
offset” is offset bytes to move the file position indicator. “
origin” from where to move the file position indicator; it could be from beginning of the file, to end of the file, from current position of the file position indicator and the valid values are SEEK_BEG, SEEK_END and SEEK_CUR respectively.
This function is mostly useful when we dealing with records in the files; records are data blocks used to store related information in the files. For example: employee record used to store an Employee related information.
In our previous article, we have seen an example which reads content of the file and display it on the screen. We have opened the file as a text file.
Another important file types we can deal with these I/O functions is binary files. Unlike, text files where information is stored in human readable form whereas binary files stores the information in binary format which is in machine readable form. Simple example is, executable file (.EXE files) are binary files and “.TXT” files are text files.
Usually binary files will occupy less disk space over the text files. For example: if we want to store a big number “2147483647” in a text file, it will occupy 10 bytes whereas to store the same number in a binary file, it occupies only 4 bytes (depends on your system) of memory.
Dealing with records
As I mentioned earlier, with these file handling functions we can deal with both text and binary files. Let’s take a simple code example. Here we are going to create a simple employee information database where the data will be stored into a “employee.dat” binary file. Below are the requirements:
Requirement 1. Maintain an employee record information in the file. Each employee record contains the following fields:
- Employee Name – It is a text field contains maximum of “50” characters.
- Age – It is an integer field.
- Employee Number – It is also an integer field.
- Salary – It is a floating point number.
Requirement 2. Employee information can be taken from the user and stored it into the “employee.dat” file.
Requirement 3. Whenever requested the information for an employee, it should read the data from “employee.dat” file and display the information on the screen.
Requirement 4. The program should be able to display Nth record from “employee.dat” file.
These are the details we have to create our simple program. With these details we came to know the following things:
- Collect the employee information from the user.
- Once user provided the information, store the information into “employee.dat” file as an employee record.
- Maintain an employee record and store/retrieve employee details to/from the database “employee.dat” file.
- Retrieve the employee record whenever user requested. Assume user may enter employee number to retrieve employee record.
- Retrieve Nth record from the database file “employee.dat” and display the Nth record information on the screen.
Let’s write our program:
Step 1. Based on above requirement, we understand that we have to use employee record to maintain employee information. So, here I am going to use ‘C’ structures to maintain employee record. ‘C’ structures are group of related fields. ‘C’ structures are created by using struct keyword. The ‘C’ code for our employee record is looks like below:
Step 2. We have to create a binary file “employee.dat” to maintain employee record information. Create the file using File Manager. Then we will use fopen to open an existing file. We have to do; read and write file operations on the file; so, we open the file in read, write binary mode. Below is the code do this:
FILE *fp = fopen("employee.dat", "rb+");
Step 3. Now ,we need to take the inputs from the user. Based on the user inputs, we have to add/update employee records in the “employee.dat” file and fetch the requested employee record and display it on the screen. This should repeat until the user wants to Quit from the application. The code looks like below:
// Take inputs from the user
printf("Enter your option here:\n");
printf("1. Add/Update Employee Record.\n");
printf("2. Fetch Employee Record.\n");
switch ( option )
// Add/Update Employee Record.
// Add the functionality here to:
// Add/Update an employee record.
// Fetch Employee Record.
// Add the functionality here to:
// Fetch Employee Record and display the information on the screen.
// Prepare for Quit. Do nothing.
case 3: break;
// Invalid input.
printf("WARNING! Invalid option.\n");
while ( option != 3 );
Step 4. When the user wants to add or update an employee record:
- First we need to check the record already exists in the “employee.dat” file, based on employee ID.
- If it is not exists, we will use fwrite function to add the record at the end of the file.
- If the record is already exists, we need to find the location where it is in the file “employee.dat”. We will update the same record using fwrite function.
long position = getrecord(emp.ID, &temp);
if ( position >= 0 )
fseek(fp, position, 0);
fseek(fp, 0L, SEEK_END);
fwrite(&emp, sizeof(emp), 1, fp);
From above code; “temp” and “emp” are the variables of type “struct Employee”. “
getrecord” is our function which checks into “employee.dat” file whether the employee record with the given employee ID is exists or not.
Note that, I am not going to give the code of “getrecord” in this article. We will discuss about the “
getrecord” code in the next article along with ‘C’ function fflush.
Step 5. If the user wants to see employee information of an employee:
- Check in the “employee.dat” file for an employee information with the given employee ID.
- Display the information on the screen.
int empid = -1;
printf("Enter Employee ID to fetch the details:\n");
struct Employee emp;
long position = getrecord(empid, &emp);
if ( position != -1 )
printf("Below are the requested Employee's details:\n");
printf("\t> Employee Name: %s\n", emp.Name);
printf("\t> Employee ID: %d\n", emp.ID);
printf("\t> Employee Age: %d\n", emp.Age);
printf("\t> Employee's Salary: $%.2f\n", emp.Salary);
printf("ERROR: Employee Record doesn't exists.\n");
Above code is self-explanatory. So, I am not giving any comments here.
Step 6. If the user wants to Quit from the application, he can enter the option 3. Make sure that the file “employee.dat” should be closed properly before exiting the application.
Let’s discuss about more in our next article.