在C ++中以块的形式读取文件时,如何处理文件末尾的部分块? ifstream :: read()只告诉我EOF已经到达,没有明显的方法可以告诉它在达到EOF之前读了多少。
即我正在尝试将此C代码移植到C ++:
FILE * fp = fopen ("myfile.bin" , "rb");
char buffer[16 * 1024 * 1024]; // 16MB buffer
while (1) {
int n = fread(buffer, 1, sizeof(buffer), fp);
if (n < sizeof(buffer)) {
// Couldn't read whole 16MB chunk;
// process the last bit of the file.
doSomething(buffer, n);
break;
}
// Have a whole 16MB chunk; process it
doSomething(buffer, sizeof(buffer));
}
这是我在C ++版本上的开始:
std::ifstream ifs("myfile.bin", std::ios::binary);
char buffer[16 * 1024 * 1024]; // 16MB buffer
while (1) {
ifs.read(buffer, sizeof(buffer));
if (ifs.eof()) {
// help!! Couldn't read whole 16MB chunk;
// but how do I process the last bit of the file?
doSomething(??????, ?????);
break;
}
// Have a whole 16MB chunk; process it
doSomething(buffer, sizeof(buffer));
}
我显然可以用C ++编译器编译C代码,但我宁愿使用现代C ++。
我能看到的唯一解决方案是逐字节读取文件 - 但文件可能是几千兆字节,所以“不是非常低效”很重要。
答案 0 :(得分:1)
流功能gcount()
可能就是你要找的东西。 cppereference webpage有一个完美的例子。以下是我编写函数的方法:
std::ifstream ifs("myfile.bin", std::ios::binary);
char buffer[16 * 1024 * 1024]; // 16MB buffer
while (1) {
ifs.read(buffer, sizeof(buffer));
if (ifs.eof()) {
// Couldn't read whole 16MB chunk;
// Process as much as we could read:
doSomething(buffer, ifs.gcount());
break;
}
// Have a whole 16MB chunk; process it
doSomething(buffer, sizeof(buffer));
}