如何从文件末尾向后读取一定数量的字节
How to read certain amount of bytes backward from end of a file C++
我正试图编写一个从文件向后读取字节的函数。我确切地知道它应该如何工作,但因为我刚开始用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
。
其次,最好避免这么多的系统调用。不是一个字节一个字节地读取,而是读取整个缓冲区或一些合理的大小,然后在内存中反转缓冲区。
相关文章:
- 从文件中读取多个字节,并将它们存储在C++中进行比较
- 在java中读取c++字节的位字段
- 读取文件中所有可能的十六进制 16 字节序列并打印每个序列
- std::ifstream::read 不会读取所有 512 字节,并设置 EOF 和失败位
- QDataStream 读取和写入的字节数比 QFile::length() 报告要多
- 如何从保存在 Java 中C++的字节数组中读取数字?
- Async_read_until限制读取的字节大小(Boost::asio)
- 如果由不同的线程写入 8 字节,那么现代英特尔 x86 上的 8 字节读取是否保证理智?
- C++ - 将任何文件的字节读取到无符号字符数组中
- InternetReadFile 填充缓冲区,但返回零字节读取
- ReadFromFile C++具有未知字节读取大小
- 从字节 [] 读取字符串
- C 如何将字节读取为整数enderness独立
- x64 CPU上的原子16字节读取
- 具有重叠I/O的FILE_FLAG_NO_BUFFERING-字节读取为零
- std::数组和字节读取
- 如何发现字节读取是日语还是英语
- 内存的字节读取:"signed char *" vs "unsigned char *"
- TCP Recv使用select()返回1字节读取
- c++字节读取问题