【问题标题】:How to read certain amount of bytes backward from end of a file C++ [duplicate]如何从文件C ++的末尾向后读取一定数量的字节[重复]
【发布时间】:2016-10-13 23:34:23
【问题描述】:

我正在尝试编写一个从文件向后读取字节的函数。我确切地知道它应该如何工作,但是因为我刚开始用 C++ 编程,所以我不知道该怎么做。

假设我有一个 2 GB 的大文件,我想将最后 800 MB 分配到系统内存中(向后)。我希望它高效;不加载整个文件,因为我不需要 1.2 GB 的空间。

到目前为止,我的知识有限,我能够写这个,但我现在卡住了。当然,必须有更优雅的方式来做到这一点。

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>

using namespace std;

int main () {
    // open the file
    ifstream file;
    file.open(filename, ios_base::binary);

    //check for successful opening
    if(!file.is_open()){
        cout << "Error." << endl;
        exit(EXIT_FAILURE);
    }

    //get the lenght of a file
    file.seekg (0, file.end);
    long length = file.tellg();
    file.seekg (0, file.beg);

    //read given amount of bytes from back and allocate them to memory
    for (long i=0; i<=bytes_to_read-1; i++) {
        file.seekg(-i, ios::end);
        file.get(c);

        //allocation process

    }
    return 0;
} 

【问题讨论】:

  • 为什么不先file.seekg(-bytes_to_read, ios::end),阅读bytes_to_read 字节,然后收工?如果你想颠倒字节顺序,读完后再颠倒。
  • @SamVarshavchik 说了什么。寻找读取的每个字节是极其低效的。这是 Windows 更新可以做的事情。
  • 我认为可能有一种方法可以在不执行额外步骤的情况下做到这一点(在内存中反转它)。我能够将所有字节加载到引用 char 数组中,但是由于字符串只有反向函数,你认为我应该实现自己的吗?有办法吗?

标签: c++ file


【解决方案1】:

使用fseek 到达您想要的位置,然后从那里读取文件。 fp 是这里的文件指针。

fseek(fp, -10, SEEK_END); // seek to the 10th byte before the end of file

如果在 C++ 中使用 iostream,则来自 http://beej.us/guide/bgc/output/html/multipage/fseek.html seekg

【讨论】:

  • fseek() 是一个 C 函数。问题是要求使用 std::ifstream 而不是 FILE* 的 C++ 解决方案。
【解决方案2】:

首先有一个错误——你需要在循环中寻找-i-1

其次,最好避免这么多系统调用。不是逐字节读取,而是读取完整的缓冲区或一些合理的大小,然后反转内存中的缓冲区。

【讨论】:

    猜你喜欢
    • 2013-03-27
    • 2011-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 2014-09-17
    • 1970-01-01
    相关资源
    最近更新 更多