#c #ofstream
#c #ofstream
Вопрос:
Эта реализация ofstream работает :
bool LinuxSysCall::addNewUser(std::string const amp;login, std::string const amp;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 amp;login, std::string const amp;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
Почему?
Комментарии:
1. В каком состоянии был поток,
out
в котором вы вызывалиopen( ... )
его?2. вероятно, это->out.is_open() вернуло значение false.
3. Пожалуйста, не используйте
this->
, когда это не нужно. Это шумно, и из-за этого ты выглядишь как программист на Си. <g>
Ответ №1:
Деструктор std::ofstream
вызовов close
. Это приведет к удалению текста в файл.
Если вы хотите использовать переменную-член (не «атрибут»), вам потребуется:
bool LinuxSysCall::addNewUser(std::string const amp;login,
std::string const amp;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;
без ее закрытия.