Linux C 重定向简单范例

//前言:我们知道printf()会将信息输出到stdout流,然后展示到屏幕上。

//那么我们所实现的简单的重定向就可以将stdout指向一个文件,然后读写,这样就达到了重定向的目的。

//code 

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <unistd.h>
 4 #include <fcntl.h>
 5 
 6 //enter F2 to get the debug window.
 7 int main(int argc,char* argv[])
 8 {
 9     /*FILE * fopen(const char * path,const char * mode);
10     返回值:文件顺利打开后,指向该流的文件指针就会被返回。
11     如果文件打开失败则返回NULL,并把错误代码存在errno 中*/
12     FILE *file = fopen("./a.out","a+");
13     if(file == NULL)
14     {
15         //fprintf(stderr,"%s","error occur when opening the file");
16     }
17     else
18     {
19         //先暂存stdout原先的流
20         void* out = stdout;
21         stdout = file;
22         printf("%s
","put data to the file!");
23         fclose(file);
24         //  
25         stdout = out;
26         printf("%s
","put data to the stdout stream");
27         exit(0);
28     }
29 }
30     

//然后去查看a.out文件内容,就可以发现多了内容"put data to the file"。

原文地址:https://www.cnblogs.com/yanwenxiong/p/4914612.html