使用fstream是否有特殊要求?

时间:2018-07-30 22:30:37

标签: c++ arrays ifstream ofstream

我想使用fstream读写数组,发生了一些错误... 写入过程的代码为:

    #include <iostream>
    #include <fstream>

    using namespace std;
    int main()
    {
       float a[4][16] = {
              3.16216,
              5.97973,
             4.18243,
             4.60135,
             2.7027,
             6.96622,
             6.50676,
             4.28378,
             5.43919,
             8.51352,
             5.30405,
             8.10135,
             2.07432,
             7.83784,
             3.67568,
             8,
             5.25197,
             8.83465,
             6.35433,
            6.65354,
        5.01575,
        7.32283,
        6.95276,
        4.50394,
        4.77165,
        8.18898,
        5.43307,
        7.65354,
        4.64567,
        8.03937,
        4.48031,
        7.49606,
        4.13333,
        6.8381,
        4.94286,
        5.09524,
        3.19048,
        6.48571,
        9.17143,
        4.78095,
        4.24762,
        8.30476,
        8.22857,
        7.33333,
        3.27619,
        9.38095,
        2.56191,
        7.44762,
        4.05195,
        6.94805,
        5.12338,
        5.35065,
        3.43507,
        6.71429,
        8.48052,
        3.94805,
        5.88312,
        8.27922,
        7.34416,
        7.81818,
        2.79221,
        8.90909,
        4.25325,
        7.26623 };

    ofstream database("test.db");
    for (int i = 0; i < 4; i++)
    {
        database.write((char *)a[i], sizeof(float) * 16);
    }
    database.close();
}

读取过程的代码为:

    float a[4][16] = { 0 };
ifstream database("test.db");
for (int i = 0; i < 4; i++)
{
    database.read((char *)a[i], sizeof(float) * 16);
    for (int j = 0; j < 16; j++)
    {
        cout << "output: " << a[i][j] << endl;
    }
}

发生了一些错误:

enter image description here

最后两个元素无法正确加载。但是,如果我更改数组的大小,例如,将a [4] [16]更改为a [4] [15],一切都会好的。有人可以给我一些建议吗,非常感谢!

1 个答案:

答案 0 :(得分:1)

由于2D数组是连续,并且由于sizeof(a)给出了整个数组的大小(以字节为单位),并且由于a是第一个数组的地址元素,您可以执行以下操作:

std::cout << "dump out\n";

{
    std::ofstream database("test.db", std::ios::binary);
    database.write(reinterpret_cast<char*>(a), sizeof(a));
}

std::cout << "read back\n";

{
    std::ifstream database("test.db", std::ios::binary);
    database.read(reinterpret_cast<char*>(a), sizeof(a));
}

注意::某些系统上需要使用std::ios::binary来防止行尾转换(数据损坏)。