Using std :: ifstream, std :: istream_iterator and std :: copy does not read the whole file

I have the following code that I used in an 188 byte file:

std::ifstream is("filename", std::ios::binary); std::vector<uint8_t> buffer; std::istream_iterator<uint8_t> i_input(is); std::copy(i_input, std::istream_iterator<uint8_t>(), std::back_inserter(buffer)); std::cout << buffer.size(); 

However, it reads only 186 bytes from 188 bytes.

I confirmed the file size in hexeditor as well as ls -al .

+4
source share
2 answers

I don't know why, but by default it seems to skip spaces. You need to disable this with noskipws :

 is >> std::noskipws; 
+11
source

What are the last two bytes? Also, you don't need istream_iterator to read binary data like this. This is redundant and probably slower than using streambuf .

See this example from an excellent answer :

 #include<iterator> // ... std::ifstream testFile("testfile", std::ios::in | std::ios::binary); std::vector<char> fileContents((std::istreambuf_iterator<char>(testFile)), std::istreambuf_iterator<char>()); 
+8
source

Source: https://habr.com/ru/post/1380521/


All Articles