简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM