【发布时间】:2015-09-25 02:46:03
【问题描述】:
在 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++。
我能看到的唯一解决方案是逐字节读取文件 - 但文件可能有几千兆字节,因此“不是效率极低”很重要。
【问题讨论】:
-
谢谢@BenjaminLindley,这完美地回答了我的问题。愿意把它写成答案,以便我接受吗?
-
不,不是。如果你愿意,你可以写一个。