0

I found many articles to this question, but none explained this in enough detail and I am still unexperienced with streams: I want to stream a file to a vector and this vector is already defined and contains some data.

This snippet seemed to work (it doesnt):

std::ifstream fileInputStream(path.wc_str(), std::ios::binary);
//byteVector contains some data and is of type: std::vector<unsigned char>*
byteVector->insert(byteVector->end(), 
  std::istream_iterator<unsigned char>(fileInputStream), 
  std::istream_iterator<unsigned char>());

In this article I found a method to get the length of my file: Using C++ filestreams (fstream), how can you determine the size of a file?

std::ifstream fileInputStream;
fileInputStream.open(path.wc_str(), std::ios::in | std::ios::binary);
fileInputStream.ignore(std::numeric_limits<std::streamsize>::max());
std::streamsize fileLength = fileInputStream.gcount();
fileInputStream.clear();   //  Since ignore will have set eof.
fileInputStream.seekg(0, std::ios_base::beg);

If I compare the vector->size from the first snippet and the fileLength from the second snippet, my vector is about 2KB short.

I want to avoid copying the data from one buffer to another, so if I need more buffers to read all data I'd prefer std::move or something similar. Someone has an idea whats wrong in my first snippet or how to accomplish this another way?

Should I read the file into another vector buffer and move that vector to the end of my first?

Natulux
  • 185
  • 1
  • 1
  • 10

1 Answers1

1

std::istream_iterator<unsigned char> is a formatted input iterator that skips whitespace, that is why your vector is short.

Use std::istreambuf_iterator<char> instead, it reads data verbatim.

Note that the meaning of the template argument is quite different between these two iterators. In the latter case it is the type of symbols decoded by std::char_traits<> (e.g. you may want to decode a utf-8 encoded file as sequence of wchar_t). std::istreambuf_iterator<char> does identity decoding. C++ streams have been using char type for representing binary data (see std::ostream::write, for example).

Maxim Egorushkin
  • 119,842
  • 14
  • 147
  • 239