Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C modifying printf () to output to a file

Tags:

c

linux

unix

printf

Is there a way to modify the printf in order to output string on a file rather than to the console?

I tried looking up something on the Internet and found calls like dup, dup2 and fflush that might be associated with this.

EDIT:

Maybe I wasn't clear.. the thing is that this was in a C exam question.. the question is as follows:

Explain how a program that normally output strings to screen (using printf()) can be made to output string to a file, without changing any code in the mentioned program.

like image 943
user1317277 Avatar asked Jun 08 '12 10:06

user1317277


2 Answers

If you do not have liberty to modify the source code that does printing, you can use freopen on stdout to redirect to a file:

stdout = freopen("my_log.txt", "w", stdout);

This borders on a hack, however, because command-line redirects will stop working as expected. If you do have access to the code that does printing, using fprintf is preferred.

You can also switch your stdout temporarily for a function call, and then put it back:

FILE *saved = stdout;
stdout = fopen("log.txt", "a");
call_function_that_prints_to_stdout();
fclose(stdout);
stdout = saved;
like image 62
Sergey Kalinichenko Avatar answered Oct 10 '22 11:10

Sergey Kalinichenko


This is usually done with I/O-redirection (... >file).

Check this little program:

#include <stdio.h>
#include <unistd.h>

int main (int argc, char *argv[]) {
    if (isatty (fileno (stdout)))
        fprintf (stderr, "output goes to terminal\n");
    else
        fprintf (stderr, "output goes to file\n");

    return 0;
}

ottj@NBL3-AEY55:~ $ ./x
output goes to terminal
ottj@NBL3-AEY55:~ $ ./x >yy
output goes to file
like image 30
ott-- Avatar answered Oct 10 '22 10:10

ott--