gpt4 book ai didi

C++为什么读取二进制文件会跳到最后

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:52:41 26 4
gpt4 key购买 nike

我有一个 178 MB 的 FORTRAN 未格式化二进制文件,我正在使用 C++ 读取该文件并将其存储在特征矩阵中。我已使用 FORTRAN 和 MATLAB 阅读文件,以确认我理解文件中的值。文件中的第一条记录是矩阵的大小。之后每条记录都以 3 个整数开头。这些整数包含数据开始的列和行以及要读取的数字数。接下来是单精度数字本身。

这是我的代码:

std::ifstream infile("MSFILE", std::ios::in | std::ios::binary);
if(!infile)
{
std::cout << "Mode shape .f12 file (MSFILE) not found\n";
exit(1);
}

int r_size1; // size of each record read
int r_size2; // size after reading for comparison

int cols, rows;
infile.read(reinterpret_cast<char *> (&r_size1), 4);
infile.read(reinterpret_cast<char *> (&cols), 4);
infile.read(reinterpret_cast<char *> (&rows), 4);
infile.read(reinterpret_cast<char *> (&r_size2), 4);

if (r_size1 != r_size2)
{
std::cout << "Error reading MSFILE\n";
exit(1);
}

MatrixXf data(rows, cols);
data.setZero();

int * vals = new int[3]; // vals holds i_col, i_row and i_word for each record
float * tempf; // pointer to array of floats that holds the data from the file

// Read in the record, and continue through the file
infile.read(reinterpret_cast<char *> (&r_size1), 4);

while (!infile.eof())
{
infile.read(reinterpret_cast<char *> (vals), 12);
tempf = new float[vals[2]];
int buf_size = vals[2] * 4;
// read the data from the file
infile.read(reinterpret_cast<char *> (tempf), buf_size);

// write the float array into the matrix
data.col(vals[0] - 1) = Map<VectorXf>(tempf, rows);

infile.read(reinterpret_cast<char *> (&r_size2), 4);

if (r_size1 != r_size2)
{
std::cout << "Error reading MSFILE\n";
exit(1);
}

delete tempf;

// finish out by reading the next record size...this will also force EOF
infile.read(reinterpret_cast<char *> (&r_size1), 4);
}

delete vals;

infile.close();

问题是第一次读取float数组时,文件走到了最后。我在每次 infile.read 之后使用 infile.tellg() 来跟踪发生了什么。一切都移动所需的数量,直到 float 数组的第一个实例。在第一个 float 组读取之后,文件进入 EOF。我希望记录包含 26130 个数字。 vals[2] 证实了这一点。 buf_size 是 104520,也就是预期的 4 * 26130。 tempf 也没有完全填充。

最佳答案

如果将二进制文件作为文本文件打开,也就是说,如果保留| std::ios::binary 超出 ifstream 的构造函数的第二个参数,然后 read 函数可能遇到一个字节序列,它解释为EOF,但它实际上只是二进制数据的一部分。

至少,这是我过去在 Microsoft 平台上读取二进制数据时遇到的问题,以及您描述的症状(读取的字节数没有预期的那么多,程序就像到达了 EOF) 与我在文本模式下读取二进制文件时从二进制文件读取“错误的 EOF”时观察到的结果一致。

关于C++为什么读取二进制文件会跳到最后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25775085/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com