alexander.sivak
alexander.sivak

Reputation: 4740

std::ifstream::read does not read all 512 bytes, and sets eof and fail bits

Please take a look at a code snippet

std::ifstream input_file(input_file_path);
char* data = new (std::nothrow) char[block_size];
if (!data)
{
    std::cout << "Failed to allocate a buffer" << '\n';
    return -1;
}
request::request_id req_id = 1U;
while (input_file)
{
    std::streamsize bytes_read = 0;
    auto bytes_to_read = block_size;
    do
    {
        input_file.read(data + bytes_read, block_size - bytes_read > 512 ? 512 : block_size - bytes_read);
        bytes_read += input_file.gcount();
    } while (input_file); // until eof

    if (input_file.eof())
    {
        std::cout << "eofbit";
    }

    if (input_file.fail())
    {
        std::cout << "failbit";
    }

    if (input_file.bad())
    {
        std::cout << "badbit";
    }

The file size is more than 8 megabytes. Code reads first 512 bytes, and 3 bytes at the second iteration. Eof and fail bits are set. What am doing wrong? Why does it execute this code like this?

Upvotes: 0

Views: 237

Answers (1)

1201ProgramAlarm
1201ProgramAlarm

Reputation: 32727

You need to open the file as a binary file:

std::ifstream input_file(input_file_path, ios::binary | ios::in);

In text mode, some characters have special meanings (CR, newline, and EOF). You file probably has an EOF character that ends the input.

Upvotes: 1

Related Questions