如何从文件末尾向后读取一定数量的字节

How to read certain amount of bytes backward from end of a file C++

本文关键字:字节 读取 文件      更新时间:2023-10-16

我正试图编写一个从文件向后读取字节的函数。我确切地知道它应该如何工作,但因为我刚开始用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;
} 

使用fseek获取您想要的位置,并从那里读取文件。fp在这里是一个文件指针。

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

from http://beej.us/guide/bgc/output/html/multipage/fseek.html, or seekg如果在c++中使用iostream

首先有一个bug—您需要在循环中查找-i-1

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