读取文件的最后X个字节

Read last X bytes of a file

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

有人能告诉我一个简单的方法吗,如何读取特定文件的最后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结尾。