Transferred from: http://www.cnblogs.com/aaronLinux/p/6765145.html?utm_source=itdadao&utm_medium=referral
Method One
#include <stdlib.h>#include <stdio.h>#include <unistd.h>#include <sys/stat.h>#include <fcntl.h>IntMain () {fflush (stdout); Setvbuf (STDOUT,NULL,_IONBF,0); printf"Test stdout\n");int save_fd = DUP (Stdout_fileno);//Save standard output File Descriptor Note: Be sure to copy a file descriptor with DUP. Don't use = like a handle under a WINODWS.int FD = open ("Test1.txt", (O_rdwr | O_creat),0644); Dup2 (Fd,stdout_fileno);//Replace the standard output printf with our newly opened file descriptor ("test file\n ); // return to standard output. Two ways //< Span style= "color: #008000;" > Method 1 has the condition of saving standard output //dup2 (Save_fd,stdout_fileno); //int ttyfd = open ( "/dev/tty", (O_RDWR), 0644 "test tty\n" );}
Method Two
#include <stdlib.h>#include <stdio.h>#include <unistd.h>IntMain () {fflush (stdout); Setvbuf (STDOUT,NULL,_IONBF,0); printf"Test stdout\n"); Freopen ("Test1.txt" w ", stdout); // Note: Do not use this type of code stdout = fopen ("Test1.txt", "w"); So the output is weird. It is best to replace it with a function such as freopen. printf ( "test file\n); Freopen ( "/dev/tty", Span style= "color: #800000;" > "w" ,stdout); printf ( "test tty\n); }
Here we can easily solve the problem of Prinft not output to the screen.
There are two different cases .
The 1th standard output is redirected.
Problem with the 2nd output buffer. Is the first two lines of code in our two cases.
Fflush (stdout); //Refresh the buffer to let it output immediately. Call it after printf and it will be output immediately.
Setvbuf (stdout,null,_ionbf,0); //If you have a problem with the last method, use this function. The buffer is directly suppressed. It is directly output.
Both of these functions are related to stream buffers. Specific use and description online there are many. I'll just say what a stream buffer is, and what it does. The operating system has set a buffer for reducing IO operations. Wait until the buffer is full and then go to Operation IO. This is to improve efficiency.
[Linux] Linux printf Output Redirect "Go"