【发布时间】:2011-06-15 22:49:55
【问题描述】:
我正在为一个项目使用 FileManager,这样阅读和写作对我来说就不那么麻烦了。或者,如果我没有花所有时间调试它。所以,这个舒适班实际上给我带来了压力和时间。惊人的。
问题似乎是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;
}
}
问题:打开失败。该文件永远不会创建,并且在写入期间我因为没有打开文件而出现异常。
FileManager::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 时,我可以很好地创建文件,但我想保持流处于读/写状态。
我怎样才能做到这一点?
【问题讨论】: