std::ofstream 不会写入文件(有时)
std::ofstream won't write to file (sometimes)
我已经讨论了许多具有相同或相似标题的问题,我以多种方式更改了代码。
我有一个非常简单的课程,只需写入文件即可。构造函数中的完全相同的代码可以在成员函数中起作用。我正在删除一些无关紧要的代码,其余的是:
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_;
构造函数无法初始化此类成员。
随后,与此类成员的比较导致不确定的行为。
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 读取文件并输入到矢量中
- 为什么有时需要将 c++ 模板函数定义放在头文件中?
- 在 h 和 cpp 文件中单独声明和实现模板有时有效,有时会出现链接器错误
- 将文本文件读取为 const char* 有时有效,有时无效
- 有时写入文本文件时会出现错误
- 静态库中的符号有时会链接到可执行文件中,有时则不会
- std::ofstream 不会写入文件(有时)
- OpenSSL:我使用存储外部文件的RSA密钥加密和解密文件,但有时我的程序会崩溃
- 我尝试用c ++编写一个bmp文件,但是bmp文件的宽度和高度似乎会影响结果,有时我得到一个坏的bmp文件