The standard logging method (in my experience) is to use stdout or stderr streams. In C ++, to use them you will need to enable iostream and use as shown 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, allows you to print only those outputs that usually end on the terminal. If you want to use these standard stream methods (which are quite readable) for output to a file, you need to redirect your output somehow. One way to do this is to use the freopen function provided by cstdio. This means that the file is open and moves the given stream to this file. See here for documentation. An example is:
#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 changed to using namespace std; for brevity only.)
You move the standard output stream stdout (which is used by cout ) to output.txt (in write mode), and you move stderr (which is used by cerr ) to error.txt also in write mode.
Hope this does the trick.
source share