The Ultimate Guide to Working with Binary Files in C
Binary Files in C
Binary files are useful to store different types of data. For example, we have details of a bank customer like account number,name of the customer and balance amount in the account. These different types of data can be stored into a structure and then written into a binary file.
struct customer
{
int accno;
char name[50];
float balance;
};
struct customer cust;
The next step is to store this structure data into binary file, as a record. This means one strcture data is written as one record into the binary file. For this purpose we can use fwrite() function whose syntax is as follows:
fwrite(address of structure variable, size, number of records to write, file pointer);
as an example to store customer structure into the binary file, we can use fwrite() as:
fwrite(&cust, sizeof(cust), 1, fp);
Here, &cust is the address of the structure variable. The second argument is its size that represents the number of bytes to be written to the file. Usually, writing one record at a time is done. So, the third argument is taken as 1. The last argument is file pointer that refers to the file.
To read data from the binary file, we can take the help of fread() function. It reads the records from the binary file, generally one record at a time.
fread(&cust, sizeof(cust), 1, fp);
This will read one record from the file and stores it into the customer structure. From the structure, the data can be sent to monitor for display.
Note:
Binary files can be opened just like text files in read, write and append mode. But we should affix ‘b’ at the end of the file mode as:
wb to write data into binary file.
rb to read data from a binary file.
ab to append data to binary file.