我想使用 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|app
或 in|out|trunc
,具体取决于您希望对现有文件发生什么情况。
关于c++ - 无法使用 boost::iostreams::file 打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37099290/