Yakov Dan
Yakov Dan

Reputation: 3372

reading binary file leaves some bytes unread

I have a binary file containing an image whose dimensions are (1908,1908,3) without any header. Each pixel is a single byte, so there should be 1908 x 1908 x 3 = 10,921,392 bytes.

I've used the following function to read the file, using iterators.

std::unique_ptr<std::vector<char>> SaliencyMapperTester::readImage(std::string filename)
{
    std::ifstream input_testcase(filename,std::ios_base::in|std::ios_base::binary);
    std::unique_ptr<std::vector<char>> vecPtr = std::unique_ptr<std::vector<char>>(new std::vector<char>());
    if (input_testcase.is_open())
        std::copy(std::istream_iterator<char>(input_testcase),std::istream_iterator<char>(),std::back_inserter(*vecPtr));
    return vecPtr;    
}

The problem is that the vector actually contains less chars than there should be. if, instead I use input_testcase.read() and provide the number of bytes to read, I get the correct result. It seems that I'm using istream_iterator incorrectly, but I can't tell what's wrong.

What's going on?

Upvotes: 2

Views: 68

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118425

You should be using std::istreambuf_iterator to read the file in this manner. This is equivalent to using read.

std::istream_iterator is equivalent to using the >> formatted extraction operator to read from the file. That will not be very useful, in this case.

Upvotes: 4

Related Questions