C++在缓冲区中读取整个文件

var*_*ard 28 c++ raii

在C++缓冲区中读取整个文件内容的好方法是什么?

虽然在普通CI中可以使用fopen(), fseek(), fread()函数组合并将整个文件读取到缓冲区,但对C++使用它仍然是个好主意吗?如果是,那么我怎样才能在打开时使用RAII方法,为缓冲区分配内存,读取和读取文件内容到缓冲区.

我应该为缓冲区创建一些包装类,它在它的析构函数中释放内存(分配给缓冲区),以及用于文件处理的相同包装器吗?

jro*_*rok 57

对于非常基本的功能,不需要包装类:

std::ifstream file("myfile", std::ios::binary | std::ios::ate);
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);

std::vector<char> buffer(size);
if (file.read(buffer.data(), size))
{
    /* worked! */
}
Run Code Online (Sandbox Code Playgroud)

  • Jamie - read()返回对ifstream本身的引用.通过在布尔上下文中使用它,你隐式调用operator bool(),它返回相同的!fail()=>这段代码是正确的 (14认同)
  • uint8_t不会比char好吗? (4认同)
  • 如果文件是二进制文件,那行得通。如果是文本,那么是的,您不能。 (4认同)
  • 你不能依赖 `tellg()` 来确定文件大小,AFAICR。 (2认同)
  • [他说你不使用`tellg()`来获取文件大小。](http://stackoverflow.com/questions/22984956/tellg-function-give-wrong-size-of-file/22986486#22986486) (2认同)

Ang*_*llo 16

您可以使用输入文件流std :: ifstream访问文件的内容,然后您可以使用std :: istreambuf_iterator迭代ifstream的内容,

std::string
getFileContent(const std::string& path)
{
  std::ifstream file(path);
  std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());

  return content;
}
Run Code Online (Sandbox Code Playgroud)

在使用迭代来构建使用ifstream的内容的新的字符串此时的IM中,std::istreambuf_iterator<char>(file)创建一个迭代器ifstream的的开头,并且std::istreambuf_iterator<char>()是一个默认构造的迭代器指示的特殊状态"结束流",其当第一个迭代器到达内容的末尾时,您将获得.


Art*_*mGr 13

我在大多数程序中都有的东西:

/** Read file into string. */
inline std::string slurp (const std::string& path) {
  std::ostringstream buf; 
  std::ifstream input (path.c_str()); 
  buf << input.rdbuf(); 
  return buf.str();
}
Run Code Online (Sandbox Code Playgroud)

可以放在标题中.
我想我在这里找到了它:https://stackoverflow.com/a/116220/257568

  • 很棒的函数名! (3认同)