fread() function in C++

In this guide, you will learn what is fread() function is in C++ programming and how to use it with an example.

1. fread() Function Overview

The fread() function is used to read data from a file into an array. It reads a specified number of elements of a particular size from the file stream and stores them in the specified memory location.

Signature:

size_t fread(void* ptr, size_t size, size_t count, FILE* stream);

Parameters:

- ptr: A pointer to the block of memory with a minimum size of (size * count bytes).

- size: The size in bytes of each element to be read.

- count: The total number of elements to be read.

- stream: Pointer to a FILE object that specifies an input stream.

2. Source Code Example

#include <iostream>
#include <cstdio>

int main() {
    FILE* fp;
    char data[20];

    // Open file in read mode
    fp = fopen("sample.txt", "r");
    if(fp == NULL) {
        std::cerr << "Error opening file.";
        return 1;
    }

    // Using fread to read data from the file
    size_t result = fread(data, 1, sizeof(data), fp);
    data[result] = '\0'; // Null-terminate the read data

    if (result > 0) {
        std::cout << "Data read from file: " << data << "\n";
    } else {
        std::cerr << "Error reading from file.";
    }

    // Close the file
    fclose(fp);

    return 0;
}

Output:

Data read from file: [contents of the sample.txt]

3. Explanation

1. We start by declaring a FILE pointer fp and a character array data of size 20.

2. We then open a file named "sample.txt" in read mode.

3. If the file opens successfully, we use fread() to read data from the file into the data array.

4. We then null-terminate the data read from the file to ensure it's a valid string.

5. The read data is then printed to the standard output.

6. After reading from the file, we close it using fclose().


Comments