Reputation: 11114
Program:
#include<stdio.h>
void main()
{
printf("Hello world\n");
}
The above program print the output as "Hello world" in stdout(Terminal). But, I need the output of the program in some other file like "output.txt". So, is there any way to change the standard output of the process to some other file via programatically.
Upvotes: 1
Views: 1250
Reputation: 1
You might want to use freopen(3) on stdout
but it would close stdout
.
You could use dup2(2) like:
int newfd = open("/tmp/someoutput.txt", O_WRONLY|O_CREAT, 0640);
if (newfd<0) {
perror("/tmp/someoutput.txt"); exit(EXIT_FAILURE); };
if (dup2(STDOUT_FILENO, newfd)) {
perror("dup2"); exit(EXIT_FAILURE); }
But as commented by David Heffernan you really want to use redirections in your shell.
IMHO redirecting STDOUT_FILENO
like above smells bad.
A possible way might be to declare a global
FILE* myout = stdout;
and use always fprintf(myout,
instead of printf(
and perhaps sometimes doing myout = fopen("/tmp/someoutput.txt");
with a test!
At least inform the user that you are redirecting his stdout
(perhaps by some message to stderr
etc...) !
Upvotes: 1
Reputation: 44926
You don't need all this stdout
changing business. Everything you have to do is to open a file and then write to it. Use fopen
and fprintf
to do it.
Upvotes: 1