当变量是属性时 ofstream 不起作用
ofstream doesn't work when the variable is an attribute
ofstream 的这个实现有效:
bool LinuxSysCall::addNewUser(std::string const &login, std::string const &password) {
std::ofstream out;
out.open(DATABASEPATH, std::ios::app);
if (out.is_open())
{
std::string str = login + ":" + password + "\n";
std::cout << "writing " << str << std::endl;
out << str;
return true;
}
return false;
}
//The new line is written in the file
但是当我将我的 std::ofstream out
作为 LinuxSysCall
的属性时,它不再起作用(没有任何例外):
bool LinuxSysCall::addNewUser(std::string const &login, std::string const &password) {
this->out.open(DATABASEPATH, std::ios::app);
if (this->out.is_open())
{
std::string str = login + ":" + password + "\n";
std::cout << "writing " << str << std::endl;
this->out << str;
return true;
}
return false;
}
//The new line is not written in the file
为什么?
std::ofstream
的析构函数调用 close
。这会将文本刷新到文件中。
如果你想使用成员变量(不是"attribute")你需要:
bool LinuxSysCall::addNewUser(std::string const &login,
std::string const &password) {
this->out.open(DATABASEPATH, std::ios::app);
if (this->out.is_open())
{
std::string str = login + ":" + password + "\n";
std::cout << "writing " << str << std::endl;
this->out << str;
this->out.close();
return true;
}
return false;
}
就目前而言,使用成员变量比使用局部变量要糟糕得多 - 但是,我怀疑您实际上想在许多成员函数之间传递打开的文件。如果是这样,您可以使用以下命令刷新输出:
this->out << std::flush;
不关闭它。
ofstream 的这个实现有效:
bool LinuxSysCall::addNewUser(std::string const &login, std::string const &password) {
std::ofstream out;
out.open(DATABASEPATH, std::ios::app);
if (out.is_open())
{
std::string str = login + ":" + password + "\n";
std::cout << "writing " << str << std::endl;
out << str;
return true;
}
return false;
}
//The new line is written in the file
但是当我将我的 std::ofstream out
作为 LinuxSysCall
的属性时,它不再起作用(没有任何例外):
bool LinuxSysCall::addNewUser(std::string const &login, std::string const &password) {
this->out.open(DATABASEPATH, std::ios::app);
if (this->out.is_open())
{
std::string str = login + ":" + password + "\n";
std::cout << "writing " << str << std::endl;
this->out << str;
return true;
}
return false;
}
//The new line is not written in the file
为什么?
std::ofstream
的析构函数调用 close
。这会将文本刷新到文件中。
如果你想使用成员变量(不是"attribute")你需要:
bool LinuxSysCall::addNewUser(std::string const &login,
std::string const &password) {
this->out.open(DATABASEPATH, std::ios::app);
if (this->out.is_open())
{
std::string str = login + ":" + password + "\n";
std::cout << "writing " << str << std::endl;
this->out << str;
this->out.close();
return true;
}
return false;
}
就目前而言,使用成员变量比使用局部变量要糟糕得多 - 但是,我怀疑您实际上想在许多成员函数之间传递打开的文件。如果是这样,您可以使用以下命令刷新输出:
this->out << std::flush;
不关闭它。