# std::fread

From cppreference.com
< cpp‎ | io‎ | c

Defined in header `<cstdio>` |  |
std::size_t fread( void* buffer, std::size_t size, std::size_t count, std::FILE* stream ); |  |

Reads up to `count` objects into the array `buffer` from the given input stream `stream` as if by calling std::fgetc `size` times for each object, and storing the results, in the order obtained, into the successive positions of `buffer`, which is reinterpreted as an array of unsigned char. The file position indicator for the stream is advanced by the number of characters read.

If the objects are not TriviallyCopyable, the behavior is undefined.

If an error occurs, the resulting value of the file position indicator for the stream is indeterminate. If a partial element is read, its value is indeterminate.

### Parameters

buffer | - | pointer to the first object in the array to be read
size | - | size of each object in bytes
count | - | the number of the objects to be read
stream | - | input file stream to read from

### Return value

Number of objects read successfully, which may be less than `count` if an error or end-of-file condition occurs.

If `size` or `count` is zero, `fread` returns zero and performs no other action.

`fread` does not distinguish between end-of-file and error, and callers must use std::feof and std::ferror to determine which occurred.

### Example

Run this code

    #include <cstddef>
    #include <cstdio>
    #include <fstream>
    #include <iostream>
    #include <vector>

    int main()
    {
        // prepare file
        std::ofstream("test.txt") << 1 << ' ' << 2 << '\n';
        std::FILE* f = std::fopen("test.txt", "r");

        std::vector<char> buf(4); // char is trivially copyable
        const std::size_t n = std::fread(&buf[0], sizeof buf[0], buf.size(), f);

        std::cout << "read " << n << " object" << (n > 1 ? "s" : "" ) << ": "
                  << std::hex << std::showbase;
        for (char n : buf)
            std::cout << static_cast<int>(n) << ' ';

        std::vector<std::string> buf2; // string is not trivially copyable
    //  This would result in undefined behavior:
    //  std::fread(&buf2[0], sizeof buf2[0], buf2.size(), f);
    }

Possible output:

    read 4 objects: 0x31 0x20 0x32 0xa

### See also

scanf fscanf sscanf | reads formatted input from stdin, a file stream or a buffer (function)
fgets | gets a character string from a file stream (function)
fwrite | writes to a file (function)

Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/io/c/fread&oldid=148707"