用C/C ++编写日志文件 [英] Writing a Log file in c/c++
问题描述
我想用c ++编写一个日志文件. 我正在处理某些事物,因此我需要维护我正在处理的事物的属性的日志,以便可以恢复到此日志文件以查看特别令我感兴趣的事物的属性. 有人可以帮助我实现这一目标吗?
I want to write a log file in c++. I am processing certain things and thus i need to maintain a log of the properties of the things that i process so that i could revert back to this log file to see the properties of anything that interests me in particular.. Could someone help me in achieving this?
推荐答案
(以我的经验)标准的日志记录方法是使用stdout或stderr流.在C ++中,要使用这些功能,您需要包含iostream,并按以下方式使用:
The standard method of logging (in my experience) is to use either the stdout or stderr streams. In C++ to use these you would need to include iostream, and use as below:
#include <iostream>
int main(int argc, char* argv[])
{
using std::cout;
using std::cerr;
using std::endl;
cout << "Output message" << endl;
cerr << "Error message" << endl;
}
但是,这只能实现到通常在终端上输出的那些输出.如果要使用这些标准流方法(可读性很强)来输出到文件,则必须以某种方式重定向输出.一种方法是使用cstdio提供的freopen
函数.这样做是打开一个文件,然后将给定的流移动到该文件.有关文档,请参见此处.一个例子是:
This, however, only achieves printing to those outputs, which usually end up at a terminal. If you want to use these standard stream methods (which are quite readable) to output to a file, then you have to redirect your output somehow. One way of doing this is by using the freopen
function, provided by cstdio. What this does is open a file, and moves a given stream to that file. See here for documentation. An example would be:
#include <iostream>
#include <cstdio>
int main(int argc, char* argv[])
{
using namespace std;
freopen( "output.txt", "w", stdout );
freopen( "error.txt", "w", stderr );
cout << "Output message" << endl;
cerr << "Error message" << endl;
}
(为简洁起见,我已更改为using namespace std;
.)
(I've changed to using namespace std;
there just for conciseness.)
您要将标准输出流stdout
(由cout
使用)移动到output.txt(在写模式下),并且您将stderr
(由cerr
使用)在写入模式下也可以访问error.txt.
You're moving the standard output stream stdout
(which is used by cout
) to output.txt (in write mode), and you're moving stderr
(which is used by cerr
) to error.txt also in write mode.
希望这能解决问题.
这篇关于用C/C ++编写日志文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!