A Complete Guide to fread() in C/C++

Filed Under: C Programming
Fread C Cpp

In this article, we’ll take a look at using fread() in C/C++.

The fread() function is very useful if you want to store the contents of reading a file into a buffer. Let’s take a look at how we can use this function, using some illustrative examples!


Basic Syntax of fread() in C/C++

This function will read a certain number of characters from a file and store in inside a buffer.

We can specify the number of characters and the buffer as well as the file.

This makes it pretty easy to read a file stream-wise and not waste your memory loading it all at once, if your file is large!

The function prototype is as follows:

size_t fread(void * buffer, size_t size, size_t count, FILE* fp);

This takes in a file pointer fp, and reads count elements, each with a size of size. This will store the contents into a buffer, passed as a void* pointer.

This will return the number of elements read. Usually, if our read is successful, we’ll get it as count. Otherwise, we’ll obviously get a number lesser than it!

Because of the return value, it is very easy to check for the EOF condition!

Let’s take a look at a simple example now, to illustrate our point.


Using fread() in C/C++ – Some simple examples

Now, we’ll take an input file containing the following content:

Hello, this is from JournalDev.
This is an article regarding the fread() function.
We'll read this file in chunks of 6 characters each!

Save this as input.txt, and we’ll pass this as a file pointer FILE* fp.

We’ll take a huge buffer size (let’s say 1024 bytes). We can pass count to be 1024, but fread() will terminate as soon as we reach EOF. Let’s verify this.

#include <stdio.h>
#include <string.h>

int main() {
    FILE* fp = fopen("input.txt", "r");

    // We'll store the contents onto a buffer
    char buffer[1024];

    // Number of characters read
    size_t num_read = fread(buffer, sizeof(char), 1024, fp);

    if (num_read < 1024) printf("Reached EOF!\n"); 
    
    // We must explicitly NULL terminate the buffer with '\0'
    buffer[num_read] = '\0';

    printf("Read %lu characters\n", num_read);

    printf("Buffer: %s\n", buffer);

    fclose(fp);
    return 0;
}

Output

Reached EOF!
Read 136 characters
Buffer: Hello, this is from JournalDev.
This is an article regarding the fread() function.
We'll read this file in chunks of 6 characters each!

Indeed, we reach EOF, since we have only 136 characters inside our file! As expected, the buffer contains the entire file.

Here, you must be very careful to NULL terminate the buffer with '\0'. fread() does NOT terminate a string by itself. That’s why we set the last element read to be \0.

Now, let’s take another case – if the file size is greater than the buffer size, we have to read the file in chunks. We’ll take count = 20, so that we read 20 characters at a time.

In this case, we’ll use fread() using a while() loop, checking it’s return value for EOF. If it has read less than 20 characters, we immediately break out of the loop and then NULL terminate the buffer string.

#include <stdio.h>
#include <string.h>

int main() {
    FILE* fp = fopen("input.txt", "r");

    // We'll store the contents onto a buffer
    char buffer[256];

    // Number of characters read
    int num_read;

    size_t total_read = 0;

    // Number of chars to read at a time
    size_t count = 20;

    while ((num_read = fread(buffer + total_read, sizeof(char), count, fp)) == count) {
        // As long as we read <count = 20> characters, we'll be in this loop
        printf("Read %lu characters (%s) into buffer\n", count, buffer + total_read);
        total_read += 20;
    }

    // If num_read is less than 6, we've reached EOF
    total_read += num_read;

    buffer[total_read] = '\0';

    printf("Read %lu characters\n", total_read);

    printf("Buffer: %s\n", buffer);

    fclose(fp);
    return 0;
}

Output

Read 20 characters (Hello, this is from ) into buffer
Read 20 characters (JournalDev.
This is ) into buffer
Read 20 characters (an article regarding) into buffer
Read 20 characters ( the fread() functio) into buffer
Read 20 characters (n.
We'll read this f) into buffer
Read 20 characters (ile in chunks of 6 c0,!Y) into buffer
Read 136 characters
Buffer: Hello, this is from JournalDev.
This is an article regarding the fread() function.
We'll read this file in chunks of 6 characters each!

While the output may look incorrect on first glance, there is no problem!

This is because fread() didn’t NULL terminate the strings, so when printing it, some garbage values were printed, since we don’t have '\0` yet, as we are still adding characters to the buffer.

So, the confirmation of the output is the final buffer itself. So indeed, we were able to read the file in chunks and print it all!


Conclusion

In this article, we looked at using fread() in C/C++. This makes it very easy to read stream-wise from an input file. It also has a very useful return value that we can use to verify terminating conditions.

References


Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages