*
<> be careful
When in Linux When a file is opened in the system , Standard input , standard output , Standard error output is turned on by default
Specify redirection file file_redirect,file_stdout( It has to be existing )
In order to verify whether the experiment is successful, you can write a sentence in the file in advance :Successful file redirection
*
<> Standard input redirection stdin 0
* use close close(0);// Turn off standard input int fd; char buf[1024];
fd=open("file_redirect",O_RDOONLY); //1. adopt printf Function to verify that standard input is redirected to a file file_redirect
printf("fd=%d",fd); //2. adopt read,write Function to verify that standard input is redirected to a file file_redirect
read(0,buf,20);// read 20 Characters to buf write(1,buf,20);// write 20 Characters to standard output close(fd);
*
<> Standard output redirection stdout 1
* use dup2 function int fd1; fd1=open("file_stdout",O_WRONLY | O_TRUNC); dup2(fd1,1);
printf("Successful file redirection"); close(fd1);
*
verification :( Execute the following command )
gcc file.c -o file
./file
cat file_stdout
*
<> Standard output redirection stdout 1
*
use fcntl function
use fcntl Functions need to be careful to turn off standard output
int fd2; fd2=open("file_stdout",O_WRONLY | O_TRUNC); close(1);
fcntl(fd2,F_DUPFD,1); printf("Successful file redirection"): close(fd2);
The verification method is the same as above
If there are deficiencies , Please point out , thank you !!!
Technology