C++ C++;如何读入具有给定偏移量的对象?

C++ C++;如何读入具有给定偏移量的对象?,c++,ifstream,fileinputstream,C++,Ifstream,Fileinputstream,现在我有了一个包含很多数据的文件。 我知道我需要的数据从位置(长)x开始,并且有一个给定的大小sizeof(y) 如何获取此数据?您应该使用fseek()将文件中的“当前位置”更改为所需的偏移量。因此,如果“f”是您的FILE*变量,offset是offset,那么调用应该是这样的(以我的泄漏内存为模): 使用seek方法: ifstream strm; strm.open ( ... ); strm.seekg (x); strm.read (buffer, y); 除了上述常用的查找和读取

现在我有了一个包含很多数据的文件。 我知道我需要的数据从位置(长)x开始,并且有一个给定的大小sizeof(y) 如何获取此数据?

您应该使用fseek()将文件中的“当前位置”更改为所需的偏移量。因此,如果“f”是您的FILE*变量,offset是offset,那么调用应该是这样的(以我的泄漏内存为模):


使用
seek
方法:

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

除了上述常用的查找和读取技术外,您还可以使用类似的方法将文件映射到进程空间,并直接访问数据

例如,给定以下数据文件“foo.dat”:

以下代码将使用基于的方法打印前四个字节后的所有文本:

#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;
}
#包括
#包括
#包括
#包括
#包括
#包括
int main()
{
int结果=-1;
int const fd=打开(“foo.dat”,仅限ordu);
结构统计;
如果(fd!=-1&&fstat(fd,&s)==0)
{
void*const addr=mmap(0,标准尺寸,保护读取,映射私有,fd,0);
if(addr!=MAP_失败)
{
char const*const text=静态_cast(addr);
//打印前4个字节后的所有文本。

std::cout@shevron,这些对象是持久化到磁盘上的吗?还是仅仅是一个包含要读取的数据的文件?
one two three
#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;
}