Unlock the Power of File Input/Output: A Deep Dive into fread()
The Basics of fread()
The fread()
function is an essential tool for reading data from files in C++. It reads a specified number of objects from a file stream, storing them in a block of memory. This function is similar to calling fgetc()
multiple times, but much more efficient.
The function takes four parameters:
- buffer: A pointer to the block of memory where the objects will be stored.
- size: The size of each object in bytes.
- count: The number of objects to read from the file stream.
- stream: The file stream to read the data from.
What Does fread() Return?
The fread()
function returns the number of objects read successfully. However, if an error occurs or the end of the file is reached, the return value may be less than the specified count
.
Example 1: fread() in Action
Suppose we have a file containing the following data:
char data[] = "Hello, World!";
FILE *fp = fopen("example.txt", "r");
char buffer[12];
size_t bytes_read = fread(buffer, 1, 12, fp);
printf("Bytes read: %zu\n", bytes_read);
printf("Buffer contents: %s\n", buffer);
fclose(fp);
When we run the program, the output will be:
Bytes read: 12
Buffer contents: Hello, World!
Example 2: fread() with Zero Count or Size
But what happens when either the count
or size
is zero? Let’s find out!
FILE *fp = fopen("example.txt", "r");
char buffer[12];
size_t bytes_read = fread(buffer, 0, 12, fp);
printf("Bytes read: %zu\n", bytes_read);
fclose(fp);
When we run the program, the output will be:
Bytes read: 0
Related Functions
If you’re working with file input/output in C++, you may also want to explore the fwrite()
and fopen()
functions. These can help you write data to files and open file streams, respectively.
By mastering the fread()
function, you’ll be able to read data from files with ease and take your C++ programming skills to the next level.