繁体   English   中英

std :: array和字节读取

[英]std::array and bytes reading

我已经读了很多关于不在C ++中使用C样式的信息,而是使用诸如std :: array,std :: vector或std :: string之类的容器。

现在,我试图读取和写入带有文件流的小型二进制文件,并将其存储在std :: array中。

看起来std :: fstream的read和write方法只能与C样式数组一起使用...

这就是我的想法:

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

typedef char byte_t;

有用。 但这是这样做的好方法吗? 如果没有,还有其他方法吗? 我应该改用byte_t []吗?

使用std::array::data

testFile.read(testArray.data(), testArray.size());
outTestFile.write(testArray.data(), testArray.size());

请注意使用.size()而不是幻数。

另外,您不需要.close()您的文件。 fstream析构函数将为您完成此任务。

暂无
暂无

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

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