c++ - 读取 filebuf 的等价物?

标签 c++ iostream

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++ 方式以二进制模式读取文件,我无法确定调用从文件中读取位的正确方法,有一个 read 用于 ifstream 但如果我应该使用该方法,那么 filebuf 有什么意义?

为了简化事情,我有一个 struct 表示顺序、大小和 header 的字段,我希望有一个方法可以只保留这个结构的实例并写入右边字段中的位就像 C 中的 fread 一样。

有人可以阐明 filebuf 的意义,以及在通过未格式化的数据流读取文件时应该使用什么方法?

最佳答案

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

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
    }
  }
}

关于c++ - 读取 filebuf 的等价物?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21049909/

相关文章:

c++ - 为什么 w/cout 不支持字符串 U/u 前缀?

c++ - 从空缓冲区构造 `std::ostream` 是否有效?

c++ - getline(cin, string) 即使使用 cin.ignore() 也不起作用

c++ - 为什么模板运算符<< 不推导出 std::endl?

c++ - OpenGL : glRotatef not working?

c++ - 编译此代码时遇到问题

c++ - 在 C++ 中调用 "new"时出现段错误?

c++ - 不带 'GetString()' 的 CString 到 std::string 的转换

c++ - 转换为 token_def 的值类型

c++ - cin.getline 将字符串的开头设置为 '\0'