C ++ - save the contents of the std :: vector <unsigned char> "file to a file
I use the function below "writeFileBytes" to write the contents of a std::vector<unsigned char> file to a file. I want to use the type "unsigned char" to save the file (note that this is done for "char"). The reason for this question is because the "unsigned char" has compatibility with any bytes (for example, "00000000"). When we use "char", we have some problems with manipulating some "invalid" characters.
See this section. What is the most suitable vector type for storing file bytes? for more information about problems with the "00000000" bits (1 byte).
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); Is there a way to use the type "unsigned char" initially to write to a file?
Does this problem really make sense?
UPDATE I:
Is there a way to use the type "unsigned char" initially to write to a file? β YES!
Following the recommendations of krzaq!
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)); } UPDATE II:
Does this problem really make sense? β In a sense, YES!
As I said below ...
The "..." unsigned char 'seems to have a "higher level of compatibility" (including bits 00000000). When we try to convert these 8 bits (bit 00000000) to 'char "we have no value as opposed to" unsigned char ". With" unsigned char "we have an invalid / unrecognized char', but we have ..."
See this topic. What is the most suitable type of vector for storing file bytes? for more information!
It doesnβt matter, char* can be used to access any data, and it will work correctly. But if you do not want to use explicit listing, perhaps 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 he will do the same, only perhaps more slowly.
Btw: you cannot pass a null pointer to write that UB.