Jones Crimson
Jones Crimson

Reputation: 47

Log the Command Line in C++

I'm trying to make a script that utilizes the command line for displaying data, and I want to be able to log everything that outputs to the command line into a separate file.

I'm using fstream, iostream, and std namespace. I just need to know how to reference the the command line CmdExample.exe and everything it's says to write it to a txt file.

Example:

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    cout << "This is some text I want to reference when the program ends" << endl << "and write to a txt file.";

    return 0;
}

Upvotes: 1

Views: 2143

Answers (1)

scohe001
scohe001

Reputation: 15446

You can use output redirection. ie:

./a.out > my_output.txt

This will put everything that would've been output to the terminal into a new file, my_output.txt (or overwrite anything already in the file).

If you want things output by cerr as well, you can modify it to be:

./a.out 2>&1 > my_output.txt #push stderr -> stdout, then stdout -> my_output.txt

Likewise, you could also use script. To use script, you would do:

script my_output.txt #start the script to my_output.txt 
./a.out #run program
exit #end script

Upvotes: 2

Related Questions