Atom
Atom

Reputation: 347

Redirecting stdout to a file in C through code

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)

Upvotes: 5

Views: 5815

Answers (3)

Ashutosh Tiwari
Ashutosh Tiwari

Reputation: 103

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

Upvotes: 0

tvanfosson
tvanfosson

Reputation: 532695

You probably want to use freopen.

Example from reference:

#include <stdio.h>
...
FILE *fp;
...
fp = freopen ("/tmp/logfile", "a+", stdout);

Upvotes: 8

Bastien L&#233;onard
Bastien L&#233;onard

Reputation: 61813

Use freopen().

Upvotes: 3

Related Questions