std :: array和bytes read

时间:2015-11-04 16:01:18

标签: c++ c++11 fstream stdarray

我已经阅读了很多关于在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 []吗?

1 个答案:

答案 0 :(得分:5)

使用std::array::data

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

请注意使用.size()代替幻数。

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

相关问题