Writing a Log file in C/C++

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;
}

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;
}

(I’ve changed to using namespace std; there just for conciseness.)

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.

Hopefully this does the trick.

Leave a Comment

techhipbettruvabetnorabahisbahis forumueduedueduseduseduedueduedusedusedus