C++以二进制流的形式读取文件,在中间随机跳过字节
C++ reading file in as binary stream, skipping byte, randomly, in middle
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()
日志多一个。我知道它发生在中间,因为我正在观看输入和输出的十六进制转储(权力的游戏不是(。
我看不出我的代码有什么问题,但我以前只是坚持 C 风格fopen
fread
fwrite
但认为是时候发展了。我相信你会在我的循环算法中找到一百万个洞,但我正在学习。谢谢和东西。
这段代码有很多问题。主要的是循环eof()
通常是错误的(请参阅这篇文章(,对于二进制输入,您不应该使用 >>
.应使用read()
(引用(,因为>>
会跳过空格,并且可能会更改行结束字符。
以下是我将如何完成此任务:
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';
}
相关文章:
- 尝试使用C++中的模板进行BST排序,但在使用随机字符串进行测试时不起作用
- 在具有随机边的图形中查找路径
- 从两端开始浏览列表,然后使用迭代器在中间停止
- 我的代码停在中间,没有错误C
- 如何在使用随机生成器(srand,rand)时检查数字是否不同
- 什么是内部::状态::输入,并且在中间定义了什么
- 在 c++ 中将随机生成的整数存储为变量
- 线程在循环的中间随机停止
- 浮点计算更改(如果存储在中间变量中"double"
- 为什么我的TicTacToe游戏在生成随机移动时会卡住
- C++ std::在中间和结尾之间插入的列表
- 单链表在中间添加节点
- 如何打印在中间包含0个字符的字符串
- C++以二进制流的形式读取文件,在中间随机跳过字节
- c++计算器atof没有错误,但它在中间一行崩溃(52)
- 为什么 c++ 编译器在中间放置空格时不输出下一行的文本?
- c++ int数组在中间以坏数据结束
- 在伪随机生成器中使用常量种子从UT和GUI中获得不相同的数字
- C++03 链接器"already defined symbol"未显示在中间文件中
- Random_shuffle算法-在没有随机生成器函数的情况下产生相同的结果