C file handling allows users to store the data from a C program to a file in either the text or the binary format. In this article, we will learn how to write a struct to a binary file in C.
Writing Structure into a Binary File in C
To write a struct to a binary file, we can use the fwrite() function that writes the given bytes of data in the file in the binary form.
Syntax of fwrite()
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
where,
- ptr: pointer to the block of memory to be written.
- size: the size of each element to be written (in bytes).
- nmemb: umber of elements.
- stream: FILE pointer to the output file stream.
Approach
- Open the binary file in write mode
- Check if the file is opened successfully. If not print error and exit.
- Specify the pointer to the struct, the size of the struct, and the number of instances.
- Write the data of the struct to the file using the frwite() method.
- Check if the write operation was successful. If not return an error.
- Close the file.
C Program to Write a Struct to a Binary File
The following program illustrates how we can write a struct to a binary file in C:
OutputStruct data written to Binary file successfully.
Time Complexity: O(1)
Auxiliary Space: O(1)