C++ 将const char*传递到构造函数中会得到null
我正在尝试制作一个简单的日志程序来记录到一个文件中,以提供有关我的程序的调试信息。我想避免使用图书馆,所以我自己做了一个。 logging.cppC++ 将const char*传递到构造函数中会得到null,c++,C++,我正在尝试制作一个简单的日志程序来记录到一个文件中,以提供有关我的程序的调试信息。我想避免使用图书馆,所以我自己做了一个。 logging.cpp #include <string.h> // String stuff #include <time.h> // Time #include "logging.hpp" // Cathooks main logging util CatLogger g_CatLogging("/tmp/nekohook.log")
#include <string.h> // String stuff
#include <time.h> // Time
#include "logging.hpp"
// Cathooks main logging util
CatLogger g_CatLogging("/tmp/nekohook.log");
//CatLogger g_CatLogging;
CatLogger::CatLogger(const char* _file_path, bool _ptime) : ptime(_ptime) {
file_path = _file_path;
}
CatLogger::~CatLogger() { fclose(log_handle); }
void CatLogger::log(const char* fmt, ...) {
// Basicly an init, because this cant be done on construct
if (log_handle == nullptr) {
log_handle = fopen(file_path, "w");
}
// Print our time if needed
if (ptime) {
// Get our time
time_t current_time = time(0);
struct tm* time_info = localtime(¤t_time);
// print it to a string
char timeString[10];
strftime(timeString, sizeof(timeString), "%H:%M:%S", time_info);
// Print the time into the log
fprintf(log_handle, "%% [%s] ", timeString);
}
// Get the string we want to log
char buffer[1024];
va_list list;
va_start(list, fmt);
vsprintf(buffer, fmt, list);
va_end(list);
// Write our log to the file
fprintf(log_handle, "%s\n", file_path, buffer);
fflush(log_handle);
// Push result var to a console here, if i ever make a console api
}
有以下几点
if (log_handle == nullptr) {
log_handle = fopen("/tmp/nekohook.log", "w");
}
它现在可以工作了,但我现在不能更改其他日志类的日志位置
编辑2:
下面是一些调试信息。不知何故,const char*没有保存到类中。这是我的主要问题
可能字符串在构造后变为空…有很多潜在的bug
if (log_handle == nullptr) {
log_handle = fopen(file_path, "w");
if(!log_handle) {
perror("File opening failed"); // check your console output.
return EXIT_FAILURE;
}
}
// Get the string we want to log
char buffer[1024];
va_list list;
va_start(list, fmt);
vsprintf(buffer, fmt, list); // potential segmentation fault
va_end(list);
用这个代替
int vsnprintf( char* buffer, std::size_t buf_size, const char* format, va_list vlist ); // (since C++11)
更重要的是,程序是多线程的。这是一个静态初始化顺序失败的例子,在调用函数之前,const char*无法初始化。
解决方案是首先将文件链接与其他文件进行比较,然后对象现在可以工作。听起来可能是静态初始化顺序的失败,如果
fopen
实现有自己的静态数据,则需要对其进行初始化才能工作。你的报告听起来像是那样失败了。建议。如果你使用C++,使用C++头文件代替C头文件。code>#include、#include
和#include
'调用g#U CatLogging global时,可能尚未初始化它。在调用main
之前是否尝试进行日志记录?使用CatLogger类的单例设计模式:要查看发生了什么,请将许多跟踪注释添加到std::cout或更好的std::cerr。
if (log_handle == nullptr) {
log_handle = fopen(file_path, "w");
if(!log_handle) {
perror("File opening failed"); // check your console output.
return EXIT_FAILURE;
}
}
// Get the string we want to log
char buffer[1024];
va_list list;
va_start(list, fmt);
vsprintf(buffer, fmt, list); // potential segmentation fault
va_end(list);
int vsnprintf( char* buffer, std::size_t buf_size, const char* format, va_list vlist ); // (since C++11)