c++ - 在 C++ 中将大数据 vector 写入/读取到二进制文件

标签 c++ vector binaryfiles

我有一个 C++ 程序,它通过将网格化的人口数据从 ascii 文件读取到一个 8640x3432 元素的 double vector 来计算给定半径内的人口。将 ascii 数据读入 vector 需要大约 30 秒(遍历每一列和每一行),而程序的其余部分只需要几秒钟。我被要求通过将人口数据写入一个二进制文件来加快这个过程,据说这样读取速度会更快。

ascii 数据文件有一些标题行,提供一些数据规范,例如列数和行数,后面是每个网格单元格的人口数据,格式为 3432 行,每行 8640 个数字,以空格分隔。人口数据数字是混合格式,可以是 0、十进制值 (0.000685648) 或科学记数法的值 (2.687768e-05)。

我找到了一些读取/写入包含 vector 的结构的示例,并尝试实现类似的东西,但遇到了问题。当我在同一个程序中写入和读取二进制文件的 vector 时,它似乎工作并为我提供了所有正确的值,但它以“段错误:11”或内存分配错误结束“未分配正在释放的指针”。如果我尝试只从以前写入的二进制文件中读取数据(而不是在同一个程序运行中重写它),那么它会给我头变量就好了,但在给我 vector 数据之前会给我一个段错误。

任何关于我可能做错了什么的建议,或者更好的方法,将不胜感激!我是在mac上编译运行的,目前没有boost之类的非标准库。 (注意:我在编码方面非常陌生,必须通过深入学习来学习,所以我可能会遗漏很多基本概念和术语——抱歉!)。

这是我想出的代码:

# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# include <fstream>
# include <iostream>
# include <vector>
# include <string.h>

using namespace std;

//Define struct for population file data and initialize one struct variable for reading in ascii (A) and one for reading in binary (B)
struct popFileData
{
    int nRows, nCol;
    vector< vector<double> > popCount; //this will end up having 3432x8640 elements
} popDataA, popDataB;

int main() {

    string gridFname = "sample";

    double dum;
    vector<double> tempVector;

    //open ascii population grid file to stream
    ifstream gridFile;
    gridFile.open(gridFname + ".asc");

    int i = 0, j = 0;

    if (gridFile.is_open())
    {
        //read in header data from file
        string fileLine;
        gridFile >> fileLine >> popDataA.nCol;
        gridFile >> fileLine >> popDataA.nRows;

        popDataA.popCount.clear();

        //read in vector data, point-by-point
        for (i = 0; i < popDataA.nRows; i++)
        {
            tempVector.clear();

            for (j = 0; j<popDataA.nCol; j++)
            {
                gridFile >> dum;
                tempVector.push_back(dum);
            }
            popDataA.popCount.push_back(tempVector);
        }
        //close ascii grid file
        gridFile.close();
    }
    else
    {
        cout << "Population file read failed!" << endl;
    }

    //create/open binary file
    ofstream ofs(gridFname + ".bin", ios::trunc | ios::binary);
    if (ofs.is_open())
    {
        //write struct to binary file then close binary file
        ofs.write((char *)&popDataA, sizeof(popDataA));
        ofs.close();
    }
    else cout << "error writing to binary file" << endl;

    //read data from binary file into popDataB struct
    ifstream ifs(gridFname + ".bin", ios::binary);
    if (ifs.is_open())
    {
        ifs.read((char *)&popDataB, sizeof(popDataB));
        ifs.close();
    }
    else cout << "error reading from binary file" << endl;

    //compare results of reading in from the ascii file and reading in from the binary file
    cout << "File Header Values:\n";
    cout << "Columns (ascii vs binary): " << popDataA.nCol << " vs. " << popDataB.nCol << endl;
    cout << "Rows (ascii vs binary):" << popDataA.nRows << " vs." << popDataB.nRows << endl;

    cout << "Spot Check Vector Values: " << endl;
    cout << "Index 0,0: " << popDataA.popCount[0][0] << " vs. " << popDataB.popCount[0][0] << endl;
    cout << "Index 3431,8639: " << popDataA.popCount[3431][8639] << " vs. " << popDataB.popCount[3431][8639] << endl;
    cout << "Index 1600,4320: " << popDataA.popCount[1600][4320] << " vs. " << popDataB.popCount[1600][4320] << endl;

    return 0;
}

这是我在同一次运行中写入和读取二进制文件时的输出:

File Header Values:
Columns (ascii vs binary): 8640 vs. 8640
Rows (ascii vs binary):3432 vs.3432
Spot Check Vector Values: 
Index 0,0: 0 vs. 0
Index 3431,8639: 0 vs. 0
Index 1600,4320: 25.2184 vs. 25.2184
a.out(11402,0x7fff77c25310) malloc: *** error for object 0x7fde9821c000: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6

下面是我尝试从预先存在的二进制文件中读取时得到的输出:

File Header Values:
Columns (binary): 8640
Rows (binary):3432
Spot Check Vector Values: 
Segmentation fault: 11

在此先感谢您的帮助!

最佳答案

当您将 popDataA 写入文件时,您正在写入 vector vector 的二进制表示形式。然而,这确实是一个非常小的对象,由一个指向实际数据的指针(在本例中它本身是一系列 vector )和一些大小信息组成。

当它被读回 popDataB 时,它可以正常工作!但只是因为 popDataA 中的原始指针现在位于 popDataB 中,并且它指向内存中的相同内容。最后事情变得疯狂,因为当 vector 的内存被释放时,代码尝试释放 popDataA 引用的数据两次(一次用于 popDataA,另一次对于 popDataB。)

简而言之,以这种方式将 vector 写入文件是不合理的。

那怎么办?最好的方法是首先决定你的数据表示。它将像 ASCII 格式一样,指定在何处写入什么值,并将包含有关矩阵大小的信息,以便您知道在读入它们时需要分配多大的 vector 。

在半伪代码中,写作看起来像这样:

int nrow=...;
int ncol=...;
ofs.write((char *)&nrow,sizeof(nrow));
ofs.write((char *)&ncol,sizeof(ncol));
for (int i=0;i<nrow;++i) {
    for (int j=0;j<ncol;++j) {
        double val=data[i][j];
        ofs.write((char *)&val,sizeof(val));
    }
}

阅读会反过来:

ifs.read((char *)&nrow,sizeof(nrow));
ifs.read((char *)&ncol,sizeof(ncol));
// allocate data-structure of size nrow x ncol
// ...
for (int i=0;i<nrow;++i) {
    for (int j=0;j<ncol;++j) {
        double val;
        ifs.read((char *)&val,sizeof(val));
        data[i][j]=val;
    }
}

尽管如此,您应该考虑不要像这样将内容写入二进制文件。这些特殊的二进制格式往往会继续存在,远远超过其预期的效用,并且往往会受到以下问题的影响:

  • 缺乏文件
  • 缺乏可扩展性
  • 没有版本控制信息的格式更改
  • 在不同机器上使用保存的数据时出现问题,包括字节顺序问题、整数的不同默认大小等。

相反,我强烈建议使用第三方库。对于科学数据,HDF5 和 netcdf4 是很好的选择,它们可以为您解决上述所有问题,并附带可以在您对特定程序一无所知的情况下检查数据的工具。

轻量级选项包括 Boost 序列化库和 Google 的 Protocol Buffer ,但它们只能解决上面列出的部分问题。

关于c++ - 在 C++ 中将大数据 vector 写入/读取到二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28886899/

相关文章:

java - 使用缓冲区读取二进制文件

python - 将二进制文件 append 到另一个二进制文件

c# - 通过注册表更改 PPPoE DSL 连接的代理设置

android - Oboe onAudioReady方法如何放大音频数据?

android - webkit 栅格与矢量图像

c++ - 使用其索引从 vector 中删除对象

c++ - 从 C++ 方法返回引用与拷贝

c++ - 使用 `extern template` 防止模板类的隐式实例化

r - R 中字符的对象大小 - R 全局字符串池如何工作?

c - 在 C 中分割文件中的二进制文件而不会损坏