0

We need to make the printf function write output on a file instead of console without involving any other function like fprintf etc.

As I understand, 1st half of the solution would be to close the console output file pointer so that printf is disabled to write any thing on console.

What next needs to be done (in C not C++) to force printf to print output on file ?

Had this been C++, would function overriding solve this purpose ?

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
  • googling gets this http://stackoverflow.com/questions/584868/rerouting-stdin-and-stdout-from-c – pm100 Oct 12 '15 at 17:32
  • _"Had this been CPP, would function overriding solve this purpose ?"_ No, not really, you would need to specify a different function signature to override (more precise overload) `printf()`. – πάντα ῥεῖ Oct 12 '15 at 17:44
  • `printf` prints to standard output, which may or may not be the console. Under any reasonable OS, you can run a program with its output redirected to a file: `program_name > output_file.txt`. Aside from that, why can't you use `fprintf`? – Keith Thompson Oct 12 '15 at 17:52

2 Answers2

1

For C code, you could use the freopen function to associate stdout with the output file:

if ( freopen( "output.txt", "w", stdout ))
{
  printf( "this should go to the output file\n" );
}
else
{
  // could not associate stdout with the output file
}
John Bode
  • 119,563
  • 19
  • 122
  • 198
  • `freopen("output.txt","a",stdout)` would be a better choice as this won't overwrite the contents(if any) in the file. – sjsam Oct 12 '15 at 17:40
0

First close stdout, then use dup2():

int fd = open("filename", O_WRONLY);
....
close(1);
dup2(fd, 1);

From the man page:

After a successful return from dup() or dup2(), the old and new file descriptors may be used interchangeably. They refer to the same open file description (see open(2)) and thus share file offset and file sta- tus flags; for example, if the file offset is modified by using lseek(2) on one of the descriptors, the offset is also changed for the other.

dbush
  • 205,898
  • 23
  • 218
  • 273