fwrite() and fread() are standard C library functions used to write and read blocks of binary data. They are commonly used to store and retrieve structures directly from files without converting them to text.
- Structures are stored in binary format, preserving the exact memory layout and improving performance.
- The file should be opened in binary mode ("wb", "rb", or "ab") when using these functions.
Binary File Modes
- rb: Opens a file for binary reading.
- wb: Opens a file for binary writing (creates a new file or overwrites an existing one).
- ab: Opens a file for appending binary data at the end of the file.
Output
Syntax
// Writing data
fwrite(ptr, size, count, file_pointer);
// Reading data
fread(ptr, size, count, file_pointer);
Parameters
- ptr: Pointer to the data to write/read.
- size: Size of each data element (usually sizeof(struct_name)).
- count: Number of elements to write/read.
- file_pointer: Pointer to the opened file.
Writing Structures to a File using fwrite
The first step for writing structures in a file is to open the file in "wb" or "ab" mode. Then, we can use the fwrite() function to easily write a structure to a file. The fwrite() function writes to the file stream in the form of a binary data block.
Output
Syntax
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
Parameters
- ptr: pointer to the block of memory to be written.
- size: the size of each element to be written (in bytes).
- nmemb: number of elements.
- stream: FILE pointer to the output file stream.
Reading Structure from a File using fread
To read structure from a file we need to open the file in "rb" binary read mode and then we can simply read structures using fread() function. This function reads a block of memory from the given stream.
Output
Syntax
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
Parameters
- ptr: pointer to the block of memory to read.
- size: the size of each element to read (in bytes).
- nmemb: number of elements.
- stream: FILE pointer to the input file stream.
Return Value: Number of objects read.
No comments:
Post a Comment