写多个数组指针与ofstream的文件?(Writing multiple array pointe

2019-09-28 03:17发布

我有一些严重的奇怪故障写入数据的多个阵列到一个文件中。 基本上,我想所有的数组的大小存储在文件的顶部,然后按照阵列中的数据。 这样我可以只读取尺寸并用它来构建磁盘阵列用来存储进口数据,我会确切地知道每个阵列的开始和结束。

这里的问题:我写的数据,但它的进口不同。 请看看我的小测试代码。 在底部也有对价值的意见。

非常感谢各位,各位程序员! :)

#include <iostream>
#include <fstream>

int main()
{
    int     jcount = 100, // First item in file
            kcount = 200, 
            in_jcount,    // Third item in file. jcount is used to find where this ends.
            in_kcount;

    float   *j = new float[jcount],
            *k = new float[kcount],
            *in_j,
            *in_k;

    for(int i = 0; i < jcount; ++i) // Write bologna data...
        j[i] = (float)i;
    for(int i = 0; i < kcount; ++i)
        k[i] = (float)i;

    std::ofstream outfile("test.dat");

    outfile.write((char*)&jcount, sizeof(int)); // Good
    outfile.tellp();

    outfile.write((char*)&kcount, sizeof(int)); // Good
    outfile.tellp();

    outfile.write((char*)j, sizeof(float) * jcount); // I don't know if this works!
    outfile.tellp();

    outfile.write((char*)k, sizeof(float) * kcount); // I don't know if this works!
    outfile.tellp();

    outfile.close();


    std::ifstream in("test.dat");

    in.read((char*)&in_jcount, sizeof(int));    // == jcount == 100, good.
    in.read((char*)&in_kcount, sizeof(int));    // == kcount == 200, good.

    in_j = new float[in_jcount],
    in_k = new float[in_kcount];    // Allocate arrays the exact size of what it should be

    in.read((char*)in_j, sizeof(float) * in_jcount);    // This is where it goes bad!
    in.read((char*)in_k, sizeof(float) * in_kcount);

    float   jtest_min = j[0],   // 0.0
            jtest_max = j[jcount - 1],  // this is 99.

            ktest_min = k[0],   // 0.0
            ktest_max = k[kcount - 1],  // this is 200. Why? It should be 199!

            in_jtest_min = in_j[0], // 0.0
            in_jtest_max = in_j[in_jcount - 1], // 99

            in_ktest_min = in_k[0], // 0.0
            in_ktest_max = in_k[in_kcount - 1]; // MIN_FLOAT, should be 199. What is going on here?

    in.close();

    delete k;
    delete j;
    delete in_j;
    delete in_k;
}

Answer 1:

没有什么明显的错误与此代码(事实上,我没有看到错误,你当我尝试运行它遇到),除了一个事实,你是不是检查错误打开输入/输出文件。

举例来说,如果你没有写权限“TEST.DAT”,开放会默默地消失,你会读回无论发生之前的文件中。



Answer 2:

我已经得到了同样的错误,我用的二进制文件修复:

ofstream outfile;
outfile.open ("test.dat", ios::out | ios::binary);

ifstream in;
in.open ("test.dat", ios::in | ios::binary);


文章来源: Writing multiple array pointers to file with ofstream?