1

In a unix/Linux environment, I'm trying to output the execution results of the cpp file to a text file instead of the console.

So I've already compiled my cpp file as follows:

  1. g++ main.cpp -o main
  2. ./main

I remember someone saying that I would the the > sign to output it to a text file , but would appreciate it if someone can help.

Tried outputting g++ main.cpp > test.txt but didn't work

  • After doing `g++ main.cpp -o main`, try `./main > test.txt` instead of `./main`. Doing `g++ main.cpp > test.txt` will not work, because that will only write the compiler output (which should be nothing) to `test.txt`. You instead want to write your program's output to `test.txt`. – Andreas Wenzel Mar 29 '23 at 01:56
  • 3
    `./main >test.txt 2>&1` if there is error output too. See [this](https://stackoverflow.com/questions/876239/how-to-redirect-and-append-both-standard-output-and-standard-error-to-a-file-wit) – ChrisD Mar 29 '23 at 02:01

1 Answers1

0

To begin with, you should distinguish between compiling and running.

So I've already compiled my cpp file as follows:

  1. g++ main.cpp -o main
  2. ./main

The first step is compiling the source file main.cpp into an executable file named main. The second step is not doing the compilation job, it's actually running the executable main.

Then, to output the running result of a command to a file, you'll do [command] >[filename] (e.g. ./main >test.txt). Essentially this associates the named file with the standard output of the program.

g++ main.cpp > test.txt will write the standard output of running g++ to test.txt, thus you get nothing. Instead you should do ./main >test.txt.

Programs often output error messages to standard error stream, in order to capture these too, you can do ./main >test.txt 2>&1.

NemoYuan2008
  • 265
  • 1
  • 7