2-3-2 跟踪文件

2.3.2 跟踪文件

本部分未被标准接收,仅作为一个技巧。

​ 跟踪文件指的是在某些情况下,将输出定位到文件中,不方便使用操作系统的重定向时。

​ 做法是:将cout通过宏变为文件的ostream对象。

//Trace.h
#ifndef TRACE_H
#define TRACE_H
#include <fstream>

#ifdef TRACEON //检测是否开启了跟踪宏
std::ofstream TRACEFILE__("TRACE.OUT");
#define cout TRACEFILE__
#endif

#endif

1. 使用案例

#include <iostream>
using namespace std;

#define TRACEON
#include "Trace.h"

int main()
{
cout<<...<<...<<endl;
}