一、简介:
在C++ 程序调试过程中,有时为了把过程中的信息和数据保存下来,可以使用写文件日志的方法。
- 头文件: #include <iostream>
#include <fstream>
- 声明: std::ofstream LogFile;
- 打开文件:LogFile.open(“log_file.txt”, std::ofstream::out);
1、C++ STL 中的定义:
void open (const char* filename, ios_base::openmode mode = ios_base::out);
void open (const string& filename, ios_base::openmode mode = ios_base::out);
2、Qt 中的定义:
void open(const char *_Filename,
ios_base::openmode _Mode = ios_base::out,
int _Prot = (int)ios_base::_Openprot)
{ // open a C stream with specified mode
if (_Filebuffer.open(_Filename, _Mode | ios_base::out, _Prot) == nullptr)
_Myios::setstate(ios_base::failbit);
else
_Myios::clear(); // added with C++11
}
void open(const string& _Str,
ios_base::openmode _Mode = ios_base::out,
int _Prot = (int)ios_base::_Openprot)
{ // open a C stream with specified mode
open(_Str.c_str(), _Mode, _Prot);
}
3、C++ STL 中的文档说明:
public member function
<fstream>
std::ofstream::open
filename
String with the name of the file to open.
Specifics about its format and validity depend on the library implementation and running environment.
mode
Flags describing the requested input/output mode for the file.
This is an object of the bitmask member type openmode that consists of a combination of the following member constants:
member constant | stands for | access |
---|---|---|
in | input | File open for reading: the internal stream buffer supports input operations. |
out * | output | File open for writing: the internal stream buffer supports output operations. |
binary | binary | Operations are performed in binary mode rather than text. |
ate | at end | The output position starts at the end of the file. |
app | append | All output operations happen at the end of the file, appending to its existing contents. |
trunc | truncate | Any contents that existed in the file before it is open are discarded. |
These flags can be combined with the bitwise OR operator (|
).
* out is always set for ofstream objects (even if explicitly not set in argument mode).
Note that even though ofstream is an output stream, its internal filebuf object may be set to also support input operations.
C++11: If the mode has both trunc and app set, the opening operation fails.
Return Value
none
If the function fails to open a file, the failbit state flag is set for the stream (which may throw ios_base::failure if that state flag was registered using member exceptions).
二、示例代码:
#include <iostream>
#include <fstream>
...
std::ofstream LogFile;
LogFile.open(“log_file.txt”, std::ofstream::out);
...
LogFile << "-------------------- Algorithm 1: CalculateMaxAggrSum() --------------------" << "\n";
LogFile << "Datetime: " << std::string(ctemp) << "\n";
LogFile << "ImageFileName: " << this->ImageFileName << "\n";
LogFile << "A1 score_rate: " << score_rate*100 << "%\n";
LogFile << "---------------------------------------------------------------------" << "\n";
...
LogFile.close();