2016-10-19 3 views
1

ときofstreamのこの実装は動作します動作しません。 ):ofstreamのは、変数が属性

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 

なぜですか?

+0

ストリームを「オープン」(...)と呼ぶ前にストリームが「出ていた」状態は何ですか? –

+0

おそらくthis-> out.is_open()はfalseを返しました。 – Joshua

+0

不要なときは 'this->'を使わないでください。それは騒々しいし、それはCプログラマのように見えるようになります。

答えて

2

デストラクタstd::ofstreamは、closeを呼び出します。これにより、テキストがファイルにフラッシュされます。

あなたはメンバ変数(ない「属性」)を使用する場合は、必要があるでしょう:

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; 

閉じることはできません。