c++ - 无法使用 boost::iostreams::file 打开文件

标签 c++ boost

我想使用 boost::iostreams::file 使用以下代码打开文件:

 boost::iostreams::file file("test.txt");
 if(!file.is_open()) {
     throw std::runtime_error("Could not open file");
 }

但它无法打开文件,我不知道为什么。当我使用 boost::iostreams::file_sink 时它可以工作。也许你知道出了什么问题?我是不是忘记了什么?我使用的是 Boost 版本 1.60

最佳答案

查看 iostreams/device/file.hpp ,我们可以看到构造函数提供了默认的in|out打开方式。

basic_file( const std::string& path,
            BOOST_IOS::openmode mode =
                BOOST_IOS::in | BOOST_IOS::out,
            BOOST_IOS::openmode base_mode =
                BOOST_IOS::in | BOOST_IOS::out );

并且它使用此模式调用 open(...) 方法。

template<typename Ch>
basic_file<Ch>::basic_file
    ( const std::string& path, BOOST_IOS::openmode mode, 
      BOOST_IOS::openmode base_mode )
{ 
    open(path, mode, base_mode);
}

然后,open(...) 方法使用此模式创建 impl 的新实例。

template<typename Ch>
void basic_file<Ch>::open
    ( const std::string& path, BOOST_IOS::openmode mode, 
      BOOST_IOS::openmode base_mode )
{ 
    pimpl_.reset(new impl(path, mode | base_mode));
}

该实现使用 std::basic_filebuf用于文件 I/O。

struct impl {
    impl(const std::string& path, BOOST_IOS::openmode mode)
        { file_.open(path.c_str(), mode); }
    ~impl() { if (file_.is_open()) file_.close(); }
    BOOST_IOSTREAMS_BASIC_FILEBUF(Ch) file_;
};

宏定义于 iostreams/detail/fstream.hpp :

# define BOOST_IOSTREAMS_BASIC_FILEBUF(Ch) std::basic_filebuf<Ch>

现在,根据std::basic_filebuf的文档(或者具体来说,它的 open(...) 方法):

openmode & ~ate  Action if file already exists    Action if file does not exist 
------------------------------------------------------------------------------
out|in           Read from start                  Error 

为了在文件不存在时创建新文件,您需要提供适当的打开模式。在您的情况下,这意味着 in|out|appin|out|trunc,具体取决于您希望对现有文件发生什么情况。

关于c++ - 无法使用 boost::iostreams::file 打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37099290/

相关文章:

linux - 链接到 Boost 时如何知道何时使用 .a 或 .so?

c++ - C++ 中的 apvectors 和 apstrings 是什么?

c++ - 为什么 boost::equals 要求范围是可复制的?

c++ - Boost 分配器的 vector 大小不正确

c++ - 可能吗? std::vector<双> my_vec(sz);已分配但未初始化或填充

c++ - 从 boost::shared_ptr 到 std::shared_ptr 的转换?

c++ - C++在目录中对文件名进行排序

c++ - 基于范围的for循环将对象 move 到另一个容器中?

c++ - Visual Studio 总是中断 "Floating-point inexact result"

python - Boost.python自动转换参数