gpt4 book ai didi

android - C++以二进制流形式读取文件,在中间随机跳过字节

转载 作者:行者123 更新时间:2023-11-28 02:38:43 25 4
gpt4 key购买 nike

std::ifstream infile;
infile.open(fullfilename, std::ios::binary);
std::vector<unsigned char> byteVect;
if (!infile.fail()) {
infile.seekg(0, std::ios_base::end);
int flsz = infile.tellg();
LOG("sz=%d, infile.fail() returned %d", flsz, infile.fail());
infile.seekg(0, std::ios_base::beg);
while (!infile.eof()) {
unsigned char byte;
infile >> byte;
if (infile.fail()) break;
byteVect.push_back(byte);
}
infile.close();
LOG("Loaded %d bytes into buffer", byteVect.size());

然后我使用我最喜欢的自制库函数将缓冲区记录到 logcat。很多零,但它仍然是早期的门。

问题是并不是所有的字节都是这样读取的。我在流的中间发现了一个丢失的字节,再见成功反序列化。我知道并非所有字节都被读取,因为有时(每当它失败时)flsz 的第一个日志比 byteVect.size() 的下一个日志多一个。我知道它发生在中间,因为我正在观察输入和输出的 hexdump(权力的游戏不是)。

我看不出我的代码有什么问题,但我以前只是坚持使用 C 风格 fopen fread fwrite 但我认为是时候进化了。我相信您会在我的循环算法中发现一百万个漏洞,但我正在学习。谢谢等等。

最佳答案

这段代码有不少问题。主要是 eof() 上的循环通常是错误的 (SEE THIS POST) 而对于二进制输入,您不应使用 >>>。你应该使用 read() (Reference) 因为 >>> 跳过空格并可能更改行结束字符。

以下是我将如何完成这项任务:

int main()
{
std::vector<unsigned char> byteVect;

std::ifstream infile;

// open file at the end (to get its length)
infile.open("test.txt", std::ios::binary|std::ios::ate);

if(!infile.is_open())
{
std::cerr << "Error opening file: " << "" << std::endl;
return 1;
}

// tellg() gives is the file position
// (and therefore length)
byteVect.resize(infile.tellg()); // make our vector big enough

if(!byteVect.empty())
{
infile.seekg(0); // move file position back to beginning

if(!infile.read((char*)&byteVect[0], byteVect.size()))
{
std::cerr << "Error reading file: " << "" << std::endl;
return 1;
}
}

infile.close();

std::cout << "Loaded " << byteVect.size() << " bytes into vector." << '\n';
}

关于android - C++以二进制流形式读取文件,在中间随机跳过字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26682728/

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