读取文件的最后X个字节

时间:2014-08-01 21:23:32

标签: c++ file-io ifstream

有人能告诉我一个简单的方法,如何读取特定文件的最后X个字节? 如果我是对的,我应该使用ifstream,但我不确定如何使用它。目前我正在学习C ++(至少我正在努力学习:))。

5 个答案:

答案 0 :(得分:3)

输入文件流具有seekg()方法,该方法将当前位置重新定位到绝对位置或相对位置。一次重载采用表示绝对值的位置类型。另一个采用偏移类型和方向掩码来确定要移动到的相对位置。取消偏移允许您向后移动。指定end常量会使指标相对于末尾移动。

file.seekg(-x, std::ios_base::end);

答案 1 :(得分:1)

您需要使用他seekg函数并从流末尾传递负偏移量。

std::ifstream is("file.txt");
if (is) 
{
   is.seekg(-x, is.end); // x is the number of bytes to read before the end
}

答案 2 :(得分:1)

这是一个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; Aborting\n");
      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; Aborting\n");
      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 %d\n", bytesRead, fileName, lastXBytes);
      if (bytesRead > 0) {
         for (i=0; i<bytesRead; i++) {
            printf("%c", buf[i]);
         }
      }
   }

   fclose(fp);
   return 0;
}

答案 3 :(得分:0)

#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;

}

答案 4 :(得分: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个字节并将它们放入缓冲区,而不添加&#39; \ 0&#39;在末尾。因此,如果您期望使用C字符串,则必须确保缓冲区以0结尾。

相关问题