clog
和 cerr
都与 stderr
相关联,但与 cerr
的区别在于 clog
中的流是缓冲的,并且不会自动与 cout
关联。
缓冲输出比非缓冲输出更有效。在缓冲输出的情况下,所有输出都会被保存到一个变量中,然后一次性写入磁盘。对于非缓冲输出,我们必须不断地写入磁盘。
缓冲输出不适合关键错误。在系统崩溃的情况下,可能会出现输出仍在缓冲区中但尚未写入磁盘,并且错误消息无法检索的情况。在系统崩溃时,我们不能承受丢失错误数据,因此即使速度较慢,我们也会将关键错误持续写入磁盘。
clog
通常用于日志记录。对于非关键事件日志记录,效率更重要,因此 clog
比 cerr
更受欢迎。
clog 声明
extern ostream clog;
它定义在 <iostream> 头文件中。
clog
对象确保在首次构造 ios_base::Init
类型对象期间或之前进行初始化。clog
不与任何其他流关联。
clog 中的“c”代表“character”(字符),因此 clog 的意思是“character log”(字符日志)。
clog 对象与插入运算符(<<)一起使用,以显示字符流。通用语法是
clog << varName;
或
clog << "Some String";
提取运算符可以多次使用,并结合变量、字符串和操纵符(如 endl
)
clog << var1 << "Some String" << var2 << endl;
示例:clog 如何工作?
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char fileName[] = "data.txt";
ifstream infile(fileName);
if(infile)
cout << infile.rdbuf();
else
clog << "Error while opening the file " << fileName << endl;
return 0;
}
在此程序中,clog 用于流式传输日志数据,因为此情况下的错误对应用程序来说并不关键。因此,使用 clog 的缓冲输出更有效。
运行程序时,输出将是 [如果打开文件时出错]
Error while opening the file data.txt