简体   繁体   中英

std::array and bytes reading

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM