The fwrite()
function in C is used to write data to a file, making it an essential tool for file handling. When working with large datasets, such as storing structured data (structs), fwrite()
becomes especially useful. Instead of saving individual data items, it allows you to save an entire structure in one go. This blog will guide you through using fwrite()
to write structures to a file in C with easy-to-understand examples.
Understanding the fwrite() Function
The fwrite()
function writes data to a file from a buffer. The syntax for fwrite()
is:
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);
- ptr: Pointer to the data to be written (in this case, a pointer to a structure).
- size: Size of each element (use
sizeof()
to calculate this for a structure). - count: Number of elements to write.
- stream: File pointer to the file where the data is to be written.
The return value is the total number of elements successfully written to the file.
How to Use fwrite() to Write a Structure to a File
To write a structure to a file, follow these steps:
- Define a structure.
- Open a file in binary write mode (
wb
). - Use
fwrite()
to write the structure to the file. - Close the file to ensure all data is flushed.
Let’s look at a practical example.
Example: Writing a Structure to a File Using fwrite()
Consider a simple structure that stores details of a person:
#include <stdio.h>
#include <stdlib.h>
struct Person {
char name[50];
int age;
float height;
};
int main() {
struct Person person = {"John Doe", 30, 5.9};
FILE *filePtr;
// Open file in write binary mode
filePtr = fopen("person.bin", "wb");
if (filePtr == NULL) {
printf("Error opening file.\n");
return 1;
}
// Write the structure to the file
fwrite(&person, sizeof(struct Person), 1, filePtr);
// Close the file
fclose(filePtr);
printf("Data written to file successfully.\n");
return 0;
}
In this program:
- We defined a structure
Person
withname
,age
, andheight
. - We opened a file named
person.bin
in binary write mode usingfopen()
. - The
fwrite()
function writes the structure data (person
) to the file. - Finally, the file is closed to save the changes.
How to Verify Data Written to the File
You can use the fread()
function to read the data back from the file and verify that it was written correctly. Here’s an example of how to read back the structure data from the file:
#include <stdio.h>
#include <stdlib.h>
struct Person {
char name[50];
int age;
float height;
};
int main() {
struct Person person;
FILE *filePtr;
// Open file in read binary mode
filePtr = fopen("person.bin", "rb");
if (filePtr == NULL) {
printf("Error opening file.\n");
return 1;
}
// Read the structure from the file
fread(&person, sizeof(struct Person), 1, filePtr);
// Display the data
printf("Name: %s\n", person.name);
printf("Age: %d\n", person.age);
printf("Height: %.2f\n", person.height);
// Close the file
fclose(filePtr);
return 0;
}
This code opens the file person.bin
, reads the structure data back into a variable, and prints it to confirm that the data was saved correctly.
Key Points to Remember
- Binary Mode: Always open the file in binary mode (
wb
orrb
) when working withfwrite()
andfread()
. This ensures the file is written in the correct format. - Structure Size: Use
sizeof(struct)
to correctly calculate the memory size needed for the structure. - Efficient Data Handling: Using
fwrite()
for structures allows for efficient file handling when working with large datasets or complex data types.
Why Use fwrite() for Writing Structures?
Using fwrite()
to write structures offers several advantages:
- Speed: Writing an entire structure in one call is faster than writing each member individually.
- Efficiency: Writing binary data is more efficient in terms of storage space compared to text data.
- Consistency: It ensures all members of a structure are written together, preserving the structure’s integrity.
The fwrite()
function in C is a powerful tool for writing structured data to files. Whether you’re working with small or large datasets, fwrite()
allows you to efficiently write data in a structured format, saving time and storage space. Understanding how to use it with structures is an essential skill for C programmers working with file I/O.