-->

C ++如何对象与给定的偏移读?(C++ How to read in objects with a

2019-06-24 06:19发布

现在我有与它的许多数据的文件。 我知道在位置(长)X我需要的数据开始,有一个给定大小的sizeof(Y)我怎样才能得到这些数据?

Answer 1:

使用seek方法:

ifstream strm;
strm.open ( ... );
strm.seekg (x);
strm.read (buffer, y);


Answer 2:

您应该使用FSEEK()在文件中改变你的“当前位置”到期望的偏移。 所以,如果“F”是你的FILE *变量,偏移补偿,这是调用应该怎么样子(我的模漏内存):

fseek(f, offset, SEEK_SET);


Answer 3:

除了一般的寻求和读取技术上面提到的,你也可以将文件映射到使用类似的进程空间的mmap()和直接访问数据。

例如,给出下面的数据文件“foo.dat”:

one two three

使用前四个字节后,下面的代码将打印所有文本的mmap()为基础的方法:

#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#include <iostream>

int main()
{
  int result = -1;

  int const fd = open("foo.dat", O_RDONLY);
  struct stat s;

  if (fd != -1 && fstat(fd, &s) == 0)
  {
    void * const addr = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
    if (addr != MAP_FAILED)
    {
       char const * const text = static_cast<char *>(addr);

       // Print all text after the first 4 bytes.
       std::cout << text + 4 << std::endl;
       munmap(addr, s.st_size);
       result = 0;
    }

    close(fd);
  }

  return result;
}

你甚至可以用这种方法来直接写入文件(记得则msync()如有必要)。

像升压和ACE库提供MMAP好的C ++封装()(与等效的Windows功能)。

这种方法可能是对小文件矫枉过正,但它可以为大文件巨大的胜利。 像往常一样,分析代码,以确定哪种方法是最好的。



文章来源: C++ How to read in objects with a given offset?