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

std::ofstream won't write to file (sometimes)

本文关键字:文件 有时 ofstream std      更新时间:2023-10-16

我已经讨论了许多具有相同或相似标题的问题,我以多种方式更改了代码。
我有一个非常简单的课程,只需写入文件即可。构造函数中的完全相同的代码可以在成员函数中起作用。我正在删除一些无关紧要的代码,其余的是:

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正在编写我想要的完全相同的日志消息,但它没有出现在文件中。该文件每次运行时都会包含一行。

在一个令人难以置信的不满意的事件中,我投票决定关闭我的问题。
这个问题显然是由无关代码中的不确定行为引起的。那是因为我做了C 11中定义的事情,但不在C 03中。显然,您无法从C 03中的构造函数调用构造函数....
因此,由于问题不包括实际上有错的代码,所以这个问题似乎非常糟糕。

请关闭。

int log_level_;

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

随后,与此类成员的比较导致不确定的行为。