1. 依賴的頭文件 2. 函數定義 3. 函數作用 + dup和dup2都可用來複制一個現存的文件描述符,使兩個文件描述符指向同一個file結構體。 + 如果兩個文件描述符指向同一個file結構體,File Status Flag和讀寫位置只保存一份在file結構體中,並且file結構體的引用計數是 ...
依賴的頭文件
#include <unistd.h>
函數定義
int dup(int oldfd); int dup2(int oldfd, int newfd);
函數作用
- dup和dup2都可用來複制一個現存的文件描述符,使兩個文件描述符指向同一個file結構體。
- 如果兩個文件描述符指向同一個file結構體,File Status Flag和讀寫位置只保存一份在file結構體中,並且file結構體的引用計數是2。
- 如果兩次open同一文件得到兩個文件描述符,則每個描述符對應一個不同的file結構體,可以有不同的File Status Flag和讀寫位置。
實戰
- 需求:在代碼中執行2次printf("hello Linux\n"),前一次輸入到world文件中,後一次輸入到屏幕上
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
void file_Redirect()
{
//先備份現場
int outfd = dup(1);
//先做重定向
int fd = open("world", O_WRONLY|O_CREAT,0666);
//標準輸出到重定向fd到對應的文件
dup2(fd, 1);
printf("hello Linux\n");
//需要來一次刷新
fflush(stdout);
//需要恢復1,重新到標準輸出
dup2(outfd, 1);
printf("hello Linux\n");
}
int main(int argc, char* argv[])
{
file_Redirect();
return 0;
}