std :: ofstream不会写入文件(有时)
问题描述:
我已经用相同或相似的标题去了很多问题,我已经在许多方面改变了代码,我甚至不能算......有一个有趣的问题。
我有一个非常简单的日志记录类,只是将东西写入文件。完全相同的代码在构造函数中工作,但在成员函数中不起作用。我剥出来一些不相干的代码,其余的是:std :: ofstream不会写入文件(有时)
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_;
构造函数无法初始化此类成员。
随后,与此类成员的比较会导致未定义的行为。
呃,那就是ctor和成员函数中的_not_完全相同的代码。事实上,它不应该编译,因为'logfile'只存在于ctor中。 –
我在这两个函数中声明了日志文件。 – xyious
@NeilButterworth有什么选择?不记录是不是。我想我可以重定向cout和cerr?节省的努力量可以忽略不计。 – xyious