【问题标题】:C++ read the whole file in buffer [duplicate]C ++读取缓冲区中的整个文件[重复]
【发布时间】:2013-09-19 21:37:30
【问题描述】:

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

虽然在纯 C 中我可以使用 fopen(), fseek(), fread() 函数组合并将整个文件读入缓冲区,但在 C++ 中使用相同的函数仍然是个好主意吗?如果是,那么我如何在打开、为缓冲区分配内存、读取和读取文件内容到缓冲区时使用 RAII 方法。

我是否应该为缓冲区创建一些包装类,在其析构函数中释放内存(为缓冲区分配),并为文件处理创建相同的包装?

【问题讨论】:

    标签: c++ raii


    【解决方案1】:

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

    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! */
    }
    

    【讨论】:

    • uint8_t 不会比 char 好吗?
    • read() 不返回布尔值。您需要检查 file.bad() (或在您的情况下为 file.good())。
    • Jamie - read() 返回对 ifstream 本身的引用。通过在布尔上下文中使用它,您可以隐式调用运算符 bool(),它返回的结果与 !fail() 相同 => 此代码是正确的
    • 文件大小不能依赖tellg(),AFAICR。
    • 如果文件是二进制文件,则可以。如果是文本,那么是的,你不能。
    【解决方案2】:

    您可以使用输入文件流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;
    }
    

    在这种情况下,我使用迭代器使用 ifstream 的内容构建一个新字符串,std::istreambuf_iterator&lt;char&gt;(file) 在 ifstream 的开头创建一个迭代器,std::istreambuf_iterator&lt;char&gt;() 是一个默认构造的迭代器,指示特殊的state "end-of-stream",当第一个迭代器到达内容的末尾时,您将得到它。

    【讨论】:

      【解决方案3】:

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

      /** 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();
      }
      

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

      【讨论】:

        猜你喜欢
        • 2012-12-09
        • 1970-01-01
        • 2016-06-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-15
        相关资源
        最近更新 更多