編程實現文件重定向

文件重定向涉及關鍵函數:函數

int dup(fd) - 新建文件描述符,指向 fd 所指向的文件;spa

int dup2(fd1, fd2) - fd2 指向 fd1 指向的文件,若fd2事先已經指向某文件,會自動斷開指向;指針

 

舉例:rest

重定向標準輸出,到一個指定的文件。code

 

代碼:blog

幾個標準文件描述符:string

標準輸入 0it

標準輸出 1io

標準錯誤 2class

 

 1 #include <stdio.h>
 2 #include <unistd.h>
 3 #include <sys/types.h>
 4 #include <sys/stat.h>
 5 #include <fcntl.h>
 6 #include <string.h>
 7 
 8 int main(int argc, char **argv)
 9 {
10         printf("before file redirect\n"); // 輸出到屏幕
11         char buf[] = "before before\n";
12         write(1, buf, strlen(buf)); // 輸出到屏幕
13 
14         int fd_stdout_bak = dup(1);
15         int fd_file = creat("file.dat", 0777);
16         int fd = dup2(fd_file, 1); // 1 指向 file.dat
17         printf("after file redirect, %s - %s\n", argv[0], argv[1]); // 輸出到文件 file.dat
18         char buf1[] = "after after\n";
19         write(1, buf1, strlen(buf1)); // 輸出到文件 file.dat
20 
21         dup2(fd_stdout_bak, 1);
22         printf("after restore stdout file\n"); // 恢復輸出到屏幕
23         char buf2[] = "restore restore\n";
24         write(1, buf2, strlen(buf2)); // 恢復輸出到屏幕
25 
26         close(fd_stdout_bak);
27         close(fd_file);
28 
29         return 0;
30 }

 

問題:

在執行標準輸出重定向前,必定要先調用 printf 函數,

若不調用此函數,則重定向失敗;

緣由不明!

 

總結:

文件描述符是指向打開的文件;

不一樣的文件描述符能夠指向同一個文件;

int close(int fd) 表示斷開文件描述符的文件指向;

總之,文件描述符相似指針;

相關文章
相關標籤/搜索