【问题标题】:Reading last bit of binary file in C++在 C++ 中读取二进制文件的最后一位
【发布时间】: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++。

我能看到的唯一解决方案是逐字节读取文件 - 但文件可能有几千兆字节,因此“不是效率极低”很重要。

【问题讨论】:

标签: c++ c++-standard-library


【解决方案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));
}

【讨论】:

    猜你喜欢
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    • 2011-09-25
    • 2017-10-01
    • 2011-09-03
    相关资源
    最近更新 更多