1

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.

mohangraj
  • 9,842
  • 19
  • 59
  • 94

3 Answers3

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...) !

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • I Experiment the following code. dup2 also not working. #include #include void main() { int fd=open("output.txt",O_CREAT,0655); dup2(1,fd); printf("Hello world\n"); } – mohangraj Oct 20 '15 at 13:13
  • You forgot to add the error testing. And I forgot the mode (3rd) argument to `open`, corrected that – Basile Starynkevitch Oct 20 '15 at 13:14
1

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.

ForceBru
  • 43,482
  • 10
  • 63
  • 98
0

You can make use of fprintf to write in a file .Open file in w or a mode and then use fprintf to write in it .

ameyCU
  • 16,489
  • 2
  • 26
  • 41