簡體   English   中英

當變量是屬性時,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 ,它不工作(不trowing任何例外):

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 這會將文本刷新到文件中。

如果要使用成員變量(而不是“屬性”),則需要:

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;

沒有關閉它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM