C modifies printf () to output to a file

Is there a way to change printf to output a line in a file, and not in the console?

I tried to find something on the Internet and found calls like dup , dup2 and fflush that could be related to this.

EDIT:

Perhaps I was unclear. The fact is that it was in the C exam question. The question is this:

Explain how a program that usually prints lines to the screen (using printf() ) can be executed to output lines to a file without changing any code in the specified program.

+4
source share
5 answers

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

Check out 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 
+5
source

If you do not have the right to change the source code that prints, you can use freopen in stdout to redirect to the file:

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

This limits hacks, as redirects from the command line will stop working as expected. If you have access to code that prints, it is preferable to use fprintf .

You can also temporarily switch your stdout to a function call, and then return it:

 FILE *saved = stdout; stdout = fopen("log.txt", "a"); call_function_that_prints_to_stdout(); fclose(stdout); stdout = saved; 
+11
source

Other answers do not cope with the problem without changing any code.

Thus, depending on the environment, the only thing left is stdout redirection when the program is called.

 ./program > target_file 
+2
source

Use either sprintf to write to a string, or to a file, or fprintf .

http://linux.die.net/man/3/fprintf

+1
source

Consulted with a lecturer, and this was the right decision (lecturer himself):

 int main { int newFile = open(desiredFilePath, O_WRONLY) if ((fork())==0) { dup2(newFile,stdout) // Explained below close newFile Set stdout as CLOSE_ON_EXEC false exec the user program } else{ Wait for child } return 0 } 

Logic dup2: here stdout is installed as a copy of newFile, which means that FD 0 is now actually a required user file, not a console. This is because the default behavior of dup 2 is to close the second filedescriptor parameter and assign it to the first parameter.

+1
source

All Articles