How to Write a Struct to a Binary File in C?
Last Updated :
27 Mar, 2024
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:
C
// C Program to illustrates how we can write a struct to a
// binary file
#include <stdio.h>
// Define a struct
struct Person {
char name[50];
int age;
float height;
};
int main()
{
// Create an instance of the struct
struct Person person = { "John", 35, 6.0 };
// Open a file in binary write mode
FILE* file = fopen("person_data.bin", "wb");
if (file == NULL) {
perror("Error opening file");
return 1;
}
// Write the struct data to the file
size_t num_written
= fwrite(&person, sizeof(struct Person), 1, file);
if (num_written != 1) {
perror("Error writing to file");
fclose(file);
return 1;
}
// Close the file
fclose(file);
printf("Struct data written to Binary file "
"successfully.\n");
return 0;
}
OutputStruct data written to Binary file successfully.
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...