gpt4 book ai didi

c++ - 如何一次从文件中读取多个字节?

转载 作者:搜寻专家 更新时间:2023-10-31 01:21:21 24 4
gpt4 key购买 nike

我想一次从二进制文件中读取 8 字节 block ,直到到达文件末尾。为什么这段代码不起作用?有哪些替代方案?

// read a file into memory
#include <iostream>
#include <fstream>
using namespace std;

int main () {

long long int * buffer;

ifstream is;
is.open ("test.txt", ios::binary );

// allocate memory:
buffer = new long long int;

// read data:
while(!is.eof())
is.read (buffer,sizeof(long long int));
is.close();


delete[] buffer;
return 0;
}

如果我将所有 long long int 替换为 char,代码将完美运行。

引用:改编自 www.cplusplus.com 的代码

最佳答案

问题是!eof : 它告诉您上一个操作是否命中eof,下一个操作是否命中,最后一个操作是否失败!

在执行 IO 后测试流本身的真实性(或使用相同的失败方法,取反):

while (is.read(buffer, sizeof(long long int))) {
// use buffer
}
assert(is.fail()); // must be true

此外,您根本不必使用 new:

long long buffer;
// ...
is.read(reinterpret_cast<char*>(&buffer), sizeof buffer)
// the reinterpret_cast is needed in your original code too

您的来源 cplusplus.com 在使用数据之前也未能检查读取是否成功。总的来说,我发现该网站非常适合列出参数、方法等,而对于其他大多数网站来说则很糟糕。


将它们放在一起,并附上一些示例输出:

#include <climits>
#include <fstream>
#include <iomanip>
#include <iostream>

int main () {
using namespace std;

ifstream in ("test.txt", in.binary);
cout << hex << setfill('0');
for (long long buffer;
in.read(reinterpret_cast<char*>(&buffer), sizeof buffer);)
{
cout << setw(sizeof buffer * CHAR_BIT / 4) << buffer << '\n';
}

return 0;
}

关于c++ - 如何一次从文件中读取多个字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3869144/

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