std :: ofstream不会写入文件(有时)

时间:2017-09-22 17:44:05

标签: c++ iostream

我已经用相同或类似的标题回答了很多问题,我已经用很多方式改变了代码,我甚至无法计算....我有一个有趣的问题。
我有一个日志记录类非常简单,只需将东西写入文件。完全相同的代码在构造函数中起作用,但在成员函数中不起作用。我正在删除一些不相关的代码,剩下的就是:

private:
    std::string logfile_path_;
    std::string program_name_;
    std::string GetTimestamp() {
        timeval tv;
        gettimeofday(&tv, NULL);
        char cTimestamp[24];
        strftime(cTimestamp, sizeof(cTimestamp), "%F %T", std::localtime(&tv.tv_sec));
        sprintf(&cTimestamp[19], ".%03d", (tv.tv_usec / 1000));         // write the miliseconds (microseconds/1000) into cTimestamp starting at the 20th character. %03d == pad with 0, for a minimum length of 3, an integer.
        return cTimestamp;      // function returns std::string so this will be implicitly cast into a string and returned.
    }

public:
    int log_level_;

    SrxDsLog(std::string Logfile_path, std::string program_name, int log_level) {
        log_level_ = log_level;
        program_name_ = program_name;
        logfile_path_ = Logfile_path;
        std::ofstream logfile(logfile_path_.c_str(), std::ios::out | std::ios::app);
        std::cout << "Logger started, Log file: " << logfile_path_ << std::endl;
        logfile << "Logger started, Log file: " << logfile_path_ << std::endl;
        return;
    }

    void WriteLog(std::string Log_message, int Severity = LOG_CRITICAL, std::string Function_name = "") {
        if (Severity >= log_level_) {
            std::cout << GetTimestamp() << "|" << program_name_ << "|" << Function_name << "|" << GetSeverity(Severity) << "|" << Log_message << std::endl;
            std::ofstream logfile(logfile_path_.c_str(), std::ios::out | std::ios::app);
            logfile << GetTimestamp() << "|" << program_name_ << "|" << Function_name << "|" << GetSeverity(Severity) << "|" << Log_message << std::endl;
        }
    }

问题是为什么它在构造函数中工作,但完全相同的代码在成员函数中不起作用。 std :: cout正在编写我想要的完全相同的日志消息,但它没有出现在文件中。每次运行程序时,该文件都包含一行。

2 个答案:

答案 0 :(得分:2)

在令人惊讶的不满意事件中,我投票决定关闭我的问题 问题显然是由不相关代码中的未定义行为引起的。那是因为我做了一些在C ++ 11中定义但不在C ++ 03中的东西。显然你不能在C ++ 03中用构造函数调用构造函数 因此,并且因为问题不包括实际上有问题的代码,问题似乎非常糟糕。

请关闭。

答案 1 :(得分:1)

int log_level_;

构造函数无法初始化此类成员。

随后,与此类成员的比较会导致未定义的行为。