1

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;
}
  • 2
    Typically you would do `CmdExample.exe > output.txt`. – nwp Sep 08 '17 at 22:24
  • 1
    Perhaps you are looking for something like https://stackoverflow.com/questions/24413744/using-operator-to-write-to-both-a-file-and-cout. – R Sahu Sep 08 '17 at 22:28

1 Answers1

2

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
scohe001
  • 15,110
  • 2
  • 31
  • 51