无法打开具有boost::iostreams::file的文件

Cannot open file with boost::iostreams::file

本文关键字:iostreams file 文件 boost      更新时间:2023-10-16

我想用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 );

并且它以这种模式调用CCD_ 2方法。

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,具体取决于您希望对现有文件执行的操作。