Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

Thinking in C++ Vol 2 - Practical Programming
Prev Home Next

Trace file

DISCLAIMER: This section and the next contain code which is officially unsanctioned by the C++ Standard. In particular, we redefine cout and new via macros, which can cause surprising results if you re not careful. Our examples work on all the compilers we use, however, and provide useful information. This is the only place in this book where we will depart from the sanctity of standard-compliant coding practice. Use at your own risk! Note that in order for this to work, a using-declaration must be used, so that cout isn t prefixed by its namespace, i.e. std::cout will not work.

The following code easily creates a trace file and sends all the output that would normally go to cout into that file. All you must do is #define TRACEON and include the header file (of course, it s fairly easy just to write the two key lines right into your file):

//: C03:Trace.h
// Creating a trace file.
#ifndef TRACE_H
#define TRACE_H
#include <fstream>
 
#ifdef TRACEON
std::ofstream TRACEFILE__("TRACE.OUT");
#define cout TRACEFILE__
#endif
 
#endif // TRACE_H ///:~
 
 

Here s a simple test of the previous file:

//: C03:Tracetst.cpp {-bor}
#include <iostream>
#include <fstream>
#include "../require.h"
using namespace std;
 
#define TRACEON
#include "Trace.h"
 
int main() {
ifstream f("Tracetst.cpp");
assure(f, "Tracetst.cpp");
cout << f.rdbuf(); // Dumps file contents to file
} ///:~
 

Because cout has been textually turned into something else by Trace.h, all the cout statements in your program now send information to the trace file. This is a convenient way of capturing your output into a file, in case your operating system doesn t make output redirection easy.

Thinking in C++ Vol 2 - Practical Programming
Prev Home Next

 
 
   Reproduced courtesy of Bruce Eckel, MindView, Inc. Design by Interspire