C++ 在linux上使用std::fstream::app写入.log文件
我正在尝试在.log文件中写入一些日志。 我的代码适用于windowsC++ 在linux上使用std::fstream::app写入.log文件,c++,linux,file,C++,Linux,File,我正在尝试在.log文件中写入一些日志。 我的代码适用于windows 在Visual Studio 2015中测试 Dev-C++ 当我登录linux并运行代码时,在多次调用此函数后,output.log文件仍然为空 bool write_log(string origin, string user, string outcome) { 这是从其他函数获取日志数 int log_id = get_log(); set_logs(++log_id); 现在我用fstrea
- 在Visual Studio 2015中测试
- Dev-C++
bool write_log(string origin, string user, string outcome) {
这是从其他函数获取日志数
int log_id = get_log();
set_logs(++log_id);
现在我用fstream打开文件:
fstream logs("outcome.log", std::fstream::in | std::fstream::app);
if (logs.is_open()) {
将日志从int转换为string,以便将其推入my string:
string log, myline;
stringstream converter; //convertng from int to string
converter << log_id;
converter >> log;
我怀疑std::fstream:app
在我使用的另一个函数std::fstream::out中,我在覆盖文件的地方使用它。在写入流后测试流的状态。我会尝试打开文件以进行输出:
std::ios_base::out | std::ios_base::app
。在指定std::ios_base::app
时,不需要打开文件进行输入(如果不应截断文件,单独使用std::ios_base::out
时需要std::ios_base::in
)。请注意,为每个日志输出打开一个文件效率极低:除非日志输出极少,否则最好保持文件打开。使用fstream::out
似乎可以工作,但如果我愿意,我不能使用getline()
。你知道为什么它在linux上不工作,但在windows上工作吗?你可能需要在写之前寻找(因为你已经读过)。@Cheersandhth.-Alf seek到我想写的地方?
myline = log + "|" + origin + "|" + user + "|" + outcome + "|"; //connecting pieces
logs << endl << myline; //inserting string to file
logs.close();
return true;
}
else {
logs.close();
cout << "Error, cannot open log file." << endl;
return false;
}
}