读取等效的filebuf吗? [英] read equivalent for filebuf?

查看:54
本文介绍了读取等效的filebuf吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

typedef struct {
  char c[20];
  int i;
} header;

void foo(std::string s) {
  std::ifstream ifs(s.c_str(), std::ios_base::binary | std::ios_base::in);
  if (ifs) {
    std::filebuf* pbuf = ifs.rdbuf();
    pbuf->pubseekpos(std::ios_base::beg); 
    // ... ?
  }
}

我正在尝试以C ++方式以二进制模式读取文件,我无法确定调用从文件中读取位的正确方法,对于ifstream有一个read,但是如果我m应该使用该方法,filebuf的意义是什么?

I'm trying to read a file in binary mode the C++ way, I can't identify the right method to call for reading the bits from the file, there is a read for ifstream but if I'm supposed to use that method, what is the point of filebuf ?

为简化起见,我有一个struct,它表示标头的顺序,大小和字段,我希望有一个方法可以保留该结构的实例,并在正确的字段中写入位就像C中的fread.

To simplify things I have a struct that represents the order, the size and the fields of the header and I hope that there will be a method that would just keep and instance of this struct and write the bits in right fields just like fread from C.

有人可以阐明filebuf的要点,以及通过无格式的数据流读取文件时应该使用哪种方法?

Someone can clarify the point of filebuf and what method should I use when reading a file through an unformatted stream of data ?

推荐答案

只需使用 basic_istream<>::read() 读取未格式化的原始字节数据:

Just use basic_istream<>::read() to read raw, unformatted byte data:

void foo(std::string s) {
  std::ifstream ifs(s.c_str(), std::ios_base::binary | std::ios_base::in);
  if (ifs) {
    char buffer[20];
    if (!ifs.read(buffer, 20)) {
      // Handle error
    }
  }
}

这篇关于读取等效的filebuf吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆