简体   繁体   English

是否可以将打印到终端的所有内容记录到C中的文本文件中?

[英]Is is possible to log everything that is printed to the terminal into a text file in C?

I have a ton of printf statements and I would like to write all of them to a text file. 我有大量的printf语句,我想将它们全部写入文本文件。 I realize I could just add fprintf statements after each one but is there a better way, such as a function, or should I just write my own function? 我意识到我可以在每个语句之后添加fprintf语句,但是有没有更好的方法,例如一个函数,还是应该编写自己的函数? I feel like this is probably a standard procedure, I just don't know what it's called, so it's hard to find an answer by googling. 我觉得这可能是一个标准程序,我只是不知道它叫什么,所以很难通过谷歌搜索找到答案。

EDIT: Just for clarity, I'd like the output to keep going the terminal like normal, but also be printed to a file simultaneously. 编辑:为了清楚起见,我希望输出像往常一样继续运行终端,但也要同时打印到文件中。 Several people are suggesting bash commands. 有几个人在建议bash命令。 When should those be executed? 这些应何时执行? After the program is run? 程序运行后?

If you're on a UNIX type box, you can pipe the output through tee , which will deliver it to standard output and a file: 如果您使用的是UNIX类型框,则可以通过tee传递输出它将输出传递到标准输出一个文件:

myProg | tee /tmp/myProg.out

There are also ways to do the same thing with standard error as well: 也可以通过标准错误执行相同的操作:

( myProg 2>&1) | tee /tmp/myProg.out_and_err

This of course depends on whatever shell you're using but that should work on the most common ones. 当然,这取决于您所使用的外壳,但应该可以在最常见的外壳上使用。

When the program is run, use the > bash operator to redirect the programs output to a text file: 程序运行时,使用> bash运算符将程序输出重定向到文本文件:

IE IE浏览器

myprogram > myfile.txt

That will save everything normally outputted to the screen with printf to a file named myfile.txt. 这会将通常使用printf输出到屏幕的所有内容保存到名为myfile.txt的文件中。

How about to redirect the stdout to a file, like 如何将标准输出重定向到文件,例如

int main ()
{
  freopen ("myfile.txt","w",stdout);
  printf ("This sentence is redirected to a file.");
  fclose (stdout);
  return 0;
}

code sample comes from c++ Reference for freopen 代码示例来自freopen的 c ++参考

You can do: ./executable > outputfile 2>&1 or ./executable &> outputfile 您可以执行以下操作: ./executable > outputfile 2>&1./executable &> outputfile

This will enable you to redirect both the standard output and the standard output to the outputfile . 这将使您能够将标准输出和标准输出都重定向到outputfile

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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