C++ 分段错误打开文件c++;
我正在尝试建立一个简单的日志系统 这是我的Log.h文件C++ 分段错误打开文件c++;,c++,C++,我正在尝试建立一个简单的日志系统 这是我的Log.h文件 #include <stdlib.h> #include <string> #include <fstream> using namespace std; class Log{ private: const static string ERROR; const static string WARNING; const static string NOTICE; c
#include <stdlib.h>
#include <string>
#include <fstream>
using namespace std;
class Log{
private:
const static string ERROR;
const static string WARNING;
const static string NOTICE;
const static string DEBUG;
const static string DEFAULT_FILENAME;
static string filename;
static ofstream* file;
public:
Log();
Log(string filename);
~Log();
void init(string filename);
static void log(string level, string msg);
static void error(string msg);
static void warning(string msg);
static void notice(string msg);
static void debug(string msg);
static Log* getInstance();
};
我编译时使用:
g++ -Wall -std=c++11 -c -o main.o main.cpp
g++ -Wall -std=c++11 -c -o Log.o Log.cpp
g++ -lfcgi++ -lfcgi main.o Log.o -o main
当我执行时,我得到:
0 foo log.txt
make: *** [exec] Segmentation fault
代码在打开文件时出错。不知何故,它不是正确的问题,因为以下代码:
ofstream myfile;
myfile.open ("log.txt");
myfile << "Writing this to a file.\n";
myfile.close();
流myfile的;
myfile.open(“log.txt”);
myfile我认为问题在于,您从未正确创建Log::file
。任何指针都必须使用new
或等效的分配器初始化。您正在对未初始化的指针调用一个方法,并且代码在那里崩溃
您的小示例之所以有效,是因为您在堆栈上分配,而不是在堆对象上分配指针。无论如何,这是解决这个问题的最好办法。除非您非常小心地管理所有权,否则使用堆分配的对象可能会在短时间内变得非常混乱
这是一种非常奇怪的使用streams的方法,其中您有一个全局静态
实例,但您也有一个类。您可能应该将流的实例移动到对象中
作为一种风格,没有必要在每个方法调用或属性引用前面放置this->
,这是隐含的。只有在名称冲突的情况下才需要这样做
以下是一些想法:
class Log {
private:
string filename;
ofstream file;
}
void Log::init(string filename_) {
filename = filename_;
cout << file << " foo " << filename << ends;
file.open(filename.c_str(), ios::out | ios::app);
cout << "bar" << std::endl;
if(!file.is_open()){
throw 10;
}
}
类日志{
私人:
字符串文件名;
流文件;
}
void Log::init(字符串文件名){
filename=filename;
当遇到错误时,第一件要做的事情是将其加载到调试器中。因为文件为NULL
。使用调试器;使用“gdb--args”运行代码我怎样才能拥有文件
非空
?不做你正在做的事..我会完成我的单例实现^^^谢谢你的回答这是你的电话。我只是建议你,使用这样的全局变量可能会导致难以预测的行为,特别是在涉及线程的情况下,这可能会导致非常棘手的调试。
ofstream myfile;
myfile.open ("log.txt");
myfile << "Writing this to a file.\n";
myfile.close();
class Log {
private:
string filename;
ofstream file;
}
void Log::init(string filename_) {
filename = filename_;
cout << file << " foo " << filename << ends;
file.open(filename.c_str(), ios::out | ios::app);
cout << "bar" << std::endl;
if(!file.is_open()){
throw 10;
}
}