Reputation: 414
I have read a lot of things about not using C-style in C++, but instead use containers like std::array, std::vector or std::string.
Now I am trying to read and write small binary files with file streams and store it in std::array.
It looks like the read and write method from std::fstream can work only with C-style arrays...
So this is what I think about:
int main(int argc, char **argv)
{
std::fstream testFile, outTestFile;
testFile.open("D:/mc_svr/another/t/world/region/r.0.0.mca", std::fstream::in | std::fstream::binary);
outTestFile.open("D:/mc_svr/another/t/world/region/xyz.xyz", std::fstream::out | std::fstream::binary);
std::array<byte_t, 8192> testArray;
testFile.read((char*) &testArray, 8192);
outTestFile.write((char*) &testArray, 8192);
testFile.close();
outTestFile.close();
return 0;
}
byte_t is just a
typedef char byte_t;
It works. But it is this the good way to do it ? If no, what are the other ways to do it ? Should I use byte_t [] instead ?
Upvotes: 1
Views: 5240
Reputation: 42828
Use std::array::data
:
testFile.read(testArray.data(), testArray.size());
outTestFile.write(testArray.data(), testArray.size());
Note the use of .size()
instead of the magic number.
Also you don't need to .close()
your files. The fstream
destructor will do that for you.
Upvotes: 5