I use the function below "writeFileBytes" to write the contents of a
std::vector<unsigned char>
void writeFileBytes(const char* filename, std::vector<unsigned char>& fileBytes){
std::ofstream file(filename, std::ios::out|std::ios::binary);
file.write(fileBytes.size() ? (char*)&fileBytes[0] : 0,
std::streamsize(fileBytes.size()));
}
writeFileBytes("xz.bin", fileBytesOutput);
void writeFileBytes(const char* filename, std::vector<unsigned char>& fileBytes){
std::ofstream file(filename, std::ios::out|std::ios::binary);
std::copy(fileBytes.cbegin(), fileBytes.cend(),
std::ostream_iterator<unsigned char>(file));
}
It doesn't matter, char*
can be used to access any kind of data and it'll work correctly. But if you don't want to use the explicit cast, maybe use std::copy
and std::ostreambuf_iterator
:
copy(fileBytes.cbegin(), fileBytes.cend(),
ostreambuf_iterator<char>(file));
alternatively, you can call
copy(fileBytes.cbegin(), fileBytes.cend(),
ostream_iterator<char>(file));
But it will do the same thing, only possibly slower.
Btw: you can't pass a null pointer to write
, that's UB.