Home > OS > Standard output is redirected to the files and the printf function
Standard output is redirected to the files and the printf function
Time:11-11
1. Use dup2 close under the Linux standard output, use printf print information, 2. The code is as follows: #include #include #include #include
Int main () { Int fd1=open (" eup. TXT ", O_RDWR | O_CREAT | O_TRUNC, 0644); If (fd1==1) { Printf (" # LINE % d: "__LINE__); Perror (" open "); return -1; } //printf (" Hello, World! \n");//do not add this sentence, eup. No content in TXT, Int fd2=dup2 (fd1, 1); If (fd2==1) { Printf (" # LINE % d: "__LINE__); Perror (" open "); return -1; } Printf (" \ \ nfd2 fd1: % d: % d nfd3: % d \ n ", fd1 and fd2, 3); Close (fd2); Close (fd1); return 0; } 3. The problem is: printf (" Hello, World! \n"); Comment out this sentence, to run the program after eup. TXT inside There is no any content, this is correct, but after uncomment, run the program, found the eup. TXT inside Is the following: Fd1:4 Fd2:1 Fd3:3 Why is this? Which function to refresh the file buffer?? First \ n cannot refresh file buffer, if is the close refresh, why annotation printf (" Hello, World! \n"); This sentence after running the program without the content refresh to eup. TXT file?? What a great god know??
CodePudding user response:
In cplusplus forum should also is you, don't know where do you see this problem, a bit much, Because of this problem, learning some function, thanks! Close () can not refresh buffer, there are clear, in this the man close and also use fsync mentioned; But the fsync to tty is invalid, so also not line,