简体   繁体   English

std :: array和字节读取

[英]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. 我已经读了很多关于不在C ++中使用C样式的信息,而是使用诸如std :: array,std :: vector或std :: string之类的容器。

Now I am trying to read and write small binary files with file streams and store it in std::array. 现在,我试图读取和写入带有文件流的小型二进制文件,并将其存储在std :: array中。

It looks like the read and write method from std::fstream can work only with C-style arrays... 看起来std :: fstream的read和write方法只能与C样式数组一起使用...

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 byte_t只是一个

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 ? 我应该改用byte_t []吗?

Use std::array::data : 使用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. 请注意使用.size()而不是幻数。

Also you don't need to .close() your files. 另外,您不需要.close()您的文件。 The fstream destructor will do that for you. fstream析构函数将为您完成此任务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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