Redirecting stdout to a file in C through code

2020-03-25 00:45发布

I am outputting to stdout. How can I redirect that to a new file through code? While we run the program we can redirect like ./sample > test.txt. How can I do this when executing the sample program itself ? (C programming)

标签: c file
3条回答
在下西门庆
2楼-- · 2020-03-25 01:25
对你真心纯属浪费
3楼-- · 2020-03-25 01:42

Use dup2() system call and redirect the output to a file.

查看更多
叼着烟拽天下
4楼-- · 2020-03-25 01:44

You probably want to use freopen.

Example from reference:

#include <stdio.h>
...
FILE *fp;
...
fp = freopen ("/tmp/logfile", "a+", stdout);
查看更多
登录 后发表回答