读取文件的最后X个字节
Read last X bytes of a file
有人能告诉我一个简单的方法吗,如何读取特定文件的最后X个字节吗?如果我是对的,我应该使用ifstream,但我不确定如何使用它。目前我正在学习C++(至少我正在努力学习:((。
输入文件流具有seekg()
方法,该方法将当前位置重新定位为绝对位置或相对位置。一个重载采用表示绝对值的positon类型。另一个采用偏移类型和方向掩码,用于确定要移动到的相对位置。抵消偏移可以向后移动。指定end
常量将使指示器相对于终点移动。
file.seekg(-x, std::ios_base::end);
这是一个C解决方案,但可以工作并处理错误。诀窍是在fseek
中使用负索引来"从EOF查找"(即:从"右侧"查找(。
#include <stdio.h>
#define BUF_SIZE (4096)
int main(void) {
int i;
const char* fileName = "test.raw";
char buf[BUF_SIZE] = { 0 };
int bytesRead = 0;
FILE* fp; /* handle for the input file */
size_t fileSize; /* size of the input file */
int lastXBytes = 100; /* number of bytes at the end-of-file to read */
/* open file as a binary file in read-only mode */
if ((fp = fopen("./test.txt", "rb")) == NULL) {
printf("Could not open input file; Abortingn");
return 1;
}
/* find out the size of the file; reset pointer to beginning of file */
fseek(fp, 0L, SEEK_END);
fileSize = ftell(fp);
fseek(fp, 0L, SEEK_SET);
/* make sure the file is big enough to read lastXBytes of data */
if (fileSize < lastXBytes) {
printf("File too small; Abortingn");
fclose(fp);
return 1;
} else {
/* read lastXBytes of file */
fseek(fp, -lastXBytes, SEEK_END);
bytesRead = fread(buf, sizeof(char), lastXBytes, fp);
printf("Read %d bytes from %s, expected %dn", bytesRead, fileName, lastXBytes);
if (bytesRead > 0) {
for (i=0; i<bytesRead; i++) {
printf("%c", buf[i]);
}
}
}
fclose(fp);
return 0;
}
您需要使用seekg
函数并从流的末尾传递一个负偏移。
std::ifstream is("file.txt");
if (is)
{
is.seekg(-x, is.end); // x is the number of bytes to read before the end
}
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv)
{
ifstream ifs("F:\test.data", ifstream::binary);
if(ifs.fail())
{
cout << "Error:fail to open file" << endl;
return -1;
}
//read the last 10 bits of file
const int X = 10;
char* buf = new char[X];
ifs.seekg(-X, SEEK_END);
ifs.read(buf, X);
ifs.close();
delete buf;
return 0;
}
使用seekg((从文件末尾进行相对定位,然后使用read((:
ifstream ifs("test.txt");
int x=10;
char buffer[11]={};
ifs.seekg(-x, ios_base::end);
if (!ifs.read(buffer, x))
cerr << "There's a problem !n";
else cout <<buffer<<endl;
请注意,read((只从文件中获取x个字节并将它们放入缓冲区,而不在末尾添加"\0"。因此,如果您期望C字符串,则必须确保缓冲区以0结尾。
相关文章:
- 从不同线程使用int64的不同字节安全吗
- 读取文件的最后一行并输入到链接列表时出错
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- lower_bound()返回最后一个元素
- 在UNIX系统中使用DIR查找文件的字节大小
- 从控制台中删除最后打印的元素
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- std::当在256字节边界上写入整数时,流的奇怪行为
- 获取向量C++中第一个值和最后一个值的和
- UDP 套接字读取最后一个传入字节
- 处理Huffman压缩/减压中的最后一个字节
- C RLE BMP压缩跳过了最后一个字节
- Qt串行端口有时会丢失最后一个字节
- 写入类的最后一个字节
- 读取文件的最后X个字节
- 有一个很长的缓冲区,但只使用最后1GB字节的数据
- 查找数组中给定索引的第一个和最后一个字节的地址
- 正在将char数组的最后8个字节设置为__uint64
- 在Arduino上使用sscan()对最后一个字节进行归零
- 使用fstream从文件中获取最后一个字节的最佳方法