How can I redirect console output to file?

2020-02-28 02:51发布

问题:

I'm new to c. Is there any simple way to redirect all the console's output (printfs etc.) to a file using some general command line \ linkage parameter (without having to modify any of the original code)?

If so what is the procedure?

回答1:

Use shell output redirection

your-command > outputfile.txt

The standard error will still be output to the console. If you don't want that, use:

your-command > outputfile.txt 2>&1

or

your-command &> outputfile.txt

You should also look into the tee utility, which can make it redirect to two places at once.



回答2:

On unices, you can also do:

your-command | tee output file.txt

That way you'll see the output and be able to interact with the program, while getting a hardcopy of the standard output (but not standard input, so it's not like a teletype session).



回答3:

As mentioned above, you can use the > operator to redirect the output of your program to a file as in:

./program > out_file

Also, you can append data to an existing file (or create it if it doesnt exit already by using >> operator:

./program >> out_file

If you really want to learn more about the (awesome) features that the command line has to offer I would really recommend reading this book (and doing lots of programming :))

http://linuxcommand.org/

Enjoy!



回答4:

In Unix shells you can usually do executable > file 2> &1, whch means "redirect standard output to file and error output to standard output"