Skip to content

Instantly share code, notes, and snippets.

@digitalresistor
Created May 15, 2011 07:16
Show Gist options
  • Save digitalresistor/972937 to your computer and use it in GitHub Desktop.
Save digitalresistor/972937 to your computer and use it in GitHub Desktop.
Why do the two reading code blocks produce different output?
#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <vector>
int main(int argc, const char *argv[]) {
{
std::ofstream outfile;
outfile.open("test", std::ios::binary);
unsigned char a[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };
unsigned char *begin = &a[0];
unsigned char *end = &a[0] + (sizeof(a));
std::copy(begin, end, std::ostream_iterator<unsigned char>(outfile));
std::cout << "Writing file with ostream_iterator: " << std::endl;
for (unsigned char *a = begin, *b = end; a != b; a++) {
std::cout << std::hex << static_cast<int>(*a) << " ";
}
std::cout << std::endl;
outfile.flush();
outfile.close();
}
// This block of code doesn't produce the same output as
{
std::ifstream infile;
infile.open("test", std::ios::binary);
std::vector<unsigned char> myVec;
infile.seekg(0, std::ios::end);
myVec.resize(infile.tellg());
infile.seekg(0);
std::copy(std::istream_iterator<unsigned char>(infile), std::istream_iterator<unsigned char>(),
myVec.begin());
std::cout << "Data read with istream_iterators: " << std::endl;
for (std::vector<unsigned char>::iterator a = myVec.begin(), b = myVec.end(); a != b; a++) {
std::cout << std::hex << static_cast<int>(*a) << " ";
}
std::cout << std::endl;
infile.close();
}
// This block of code ...
{
std::ifstream infile;
infile.open("test", std::ios::binary);
std::vector<unsigned char> myVec;
char a;
while (infile.read(&a, 1)) {
myVec.push_back(static_cast<unsigned char>(a));
}
std::cout << "Data read with .read(): " << std::endl;
for (std::vector<unsigned char>::iterator a = myVec.begin(), b = myVec.end(); a != b; a++) {
std::cout << std::hex << static_cast<int>(*a) << " ";
}
std::cout << std::endl;
infile.close();
}
// Yet I would expect them to have the same result. Both should be reading from the input file,
// and copying it to the vector.
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment