我正在为项目使用FileManager,因此阅读和写作对我来说不是一件麻烦事。或者,如果我没有花这么多时间调试它。所以,这种舒适等级实际上给我带来了压力和时间。真棒。Fstream无法创建新文件
问题似乎是fstream
。在继续进行之前,这里是我的FileManager类的结构。
class FileManager : Utility::Uncopyable
{
public:
FileManager();
void open(std::string const& filename);
void close();
void read(std::string& buffer);
void write(std::string const& data);
private:
std::fstream stream_;
};
很简单。在读取功能期间,缓冲区会载入数据,数据参数是要写入文件的内容。在阅读和写作之前,你必须打开文件或冒险得到一个大的,胖的例外。有点像我现在得到的那个。
场景:简单的命令行注册用户,然后将数据写入文件。我要求一个名字和密码。该名称被复制并附加.txt(文件名)。所以它看起来像这样:
void SessionManager::writeToFile(std::string const& name,
std::string const& password)
{
std::string filename = name + ".txt";
std::string data;
data += name +", " +password;
try
{
fileManager_->open(filename);
fileManager_->write(data);
fileManager_->close();
}
catch(FileException& exception)
{
/* Clean it up. */
std::cerr << exception.what() << "\n";
throw;
}
}
问题:打开失败。该文件从不创建,并且在写入期间,我得到一个没有打开文件的例外。
文件管理:: open()函数:
void FileManager::open(std::string const& filename)
{
if(stream_.is_open())
stream_.close();
stream_.open(filename.c_str());
}
,写
void FileManager::write(std::string const& data)
{
if(stream_.is_open())
stream_ << data;
else
throw FileException("Error. No file opened.\n");
}
但是,如果我事先创建的文件,那么它就没有烦恼打开该文件。但是,当我检查时,默认std::ios::openmode
是std::ios::in | std::ios::out
。当我只标记std::ios::out
时,我可以创建该文件,但我希望保持流处于读/写状态。
我该如何做到这一点?
由于C++ 11,`ios_base :: app`本身是允许的,并且等同于“a”。有关更新的表,请参见C++ 11或C++ 14中的表132。 – 2016-01-29 00:19:30