【发布时间】: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 数组中,但是由于字符串只有反向函数,你认为我应该实现自己的吗?有办法吗?