C语言 如何将控制台输出重定向到文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20155744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I redirect console output to file?
提问by vondip
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)?
我是 c 的新手。是否有任何简单的方法可以使用一些通用命令行 \ 链接参数(无需修改任何原始代码)将所有控制台的输出(printfs 等)重定向到文件?
If so what is the procedure?
如果是这样,程序是什么?
回答by Hut8
Use shell output redirection
使用 shell 输出重定向
your-command > outputfile.txt
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
your-command > outputfile.txt 2>&1
or
或者
your-command &> outputfile.txt
your-command &> outputfile.txt
You should also look into the teeutility, which can make it redirect to two places at once.
您还应该查看该tee实用程序,它可以使其一次重定向到两个位置。
回答by Reinstate Monica
On unices, you can also do:
在 unices 上,您还可以执行以下操作:
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).
这样,您将看到输出并能够与程序进行交互,同时获得标准输出的硬拷贝(但不是标准输入,因此它不像电传会话)。
回答by Andrés AG
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 :))
如果您真的想了解有关命令行必须提供的(很棒的)功能的更多信息,我真的建议您阅读本书(并进行大量编程:))
Enjoy!
享受!
回答by gpeche
In Unix shells you can usually do executable > file 2> &1, whch means "redirect standard output to fileand error output to standard output"
在 Unix shell 中,您通常可以这样做executable > file 2> &1,这意味着“将标准输出重定向到文件并将错误输出重定向到标准输出”

