我想读取一个包含 5 个 ID 的起始序列 char[9] 和 char[5] 的二进制文件。所以我打开了我的文件,但我不确定如何正确保存我的数据。
char[8] start_sq = "STARTSEQ\n" // start of the binary file
之后有 5 个 ID。
那么如何在 start_sq 之后设置我的起始位置
int current_pos = 0;
std:ifstream readFile_;
int *id;
while( (current_pos = (readFile_.tellg())) == eof)
{
//start after start_sq // not sure how to
int tmp_id = readFile_.read(reinterpret_cast<char*>(&id), sizeof(int)); // should be first ID (OR?)
ids.push_back(tmo_id);
// again for ID 2
}
我明白了,如果我的问题一开始有点不清楚。但我不确定如何正确实现。但如您所见,我有一些想法/方法。
感谢任何帮助:)
最佳答案
是的,你会这样做:
[ 警告:以下内容绝对未经测试! ]
//int current_pos = 0;
std:ifstream readFile_;
... // Open the file in binary mode, etc...
//int *id;
char id;
// Read the 'STARTSEQ' string + 1 carriage return :
char[9] startseq;
readFile_.read(reinterpret_cast<char*>(&startseq[0]), 9);
// ^^^
// IMPORTANT : The above line shifts the current_pos of 9 bytes.
// Short : readFile_.read(startseq, sizeof(startseq));
// Then read your IDs
// You want your IDs as chars so let's read chars, not int.
while( readFile_.good() ) // or while( !readFile_.eof() )
{
readFile_.read(reinterpret_cast<char*>(&id), sizeof(char));
// IMPORTANT : The above line shifts the current_pos of 1 byte.
// Short : readFile_.read(&id, 1);
ids.push_back(id);
}
// The above 'while' loops until EOF is reached (aka. 5 times).
// See ifstream.good(), ifstream.eof().
注意:要读取的字符串(“STARTSEQ\n”)长度为 9 个字符,而不是 8 个。
填充 ids
vector 的另一种方法可能是:
vector<char> ids;
int size = 5;
ids.resize(size);
// Read 'size' bytes (= chars) and store it in the 'ids' vector :
readFile_.read(reinterpret_cast<char*>(&ids[0]), size);
注意:这里没有使用while
,但注意:不检查是否到达EOF。
我希望这是你所要求的。
关于C++读取配置二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17180423/