-
依賴的頭檔案
#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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/124014.html
標籤:Linux
