我正在學習作業系統課程并在 Linux 上使用 C 做作業。在其中一項作業中,我應該重定向并輸出到一個檔案,但由于某種原因,我一直在終端中獲取輸出。我嘗試撰寫一個簡單的程式來做到這一點,但它仍然不起作用:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/fcntl.h>
#include <dirent.h>
void main(int argc, char* argv[]) {
int file1 = open("./text_try", O_CREAT | O_EXCL, 0666) //open file
printf("write to screen\n"); //print to screen
int oldOut = dup(1); //save screen FD
dup2(file1,1); //change output stream from screen to file
printf("write to file"); //print to file
dup2(oldOut,1); //change output stream from file back screen
printf("write to screen"); //print to screen
}
我嘗試過的其他事情:
- 更改打開檔案的權限(添加
O_RDWR) - 在 2 臺獨立的 PC 上運行 - 我主要在遠程桌面上運行到適用于 linux 的 uni pc,但也在筆記本電腦上安裝了 VMware。
- 嘗試使用
closedup組合代替dup2 - 嘗試使用條件 with
perror來查看是否有任何步驟會提示我為什么它不起作用。 - 嘗試使用
STDOUT_FILENO而不是 1 進行輸出
非常感謝您對此的任何幫助!
uj5u.com熱心網友回復:
stdio 通常將輸出緩沖到stdout——當它連接到終端時是行緩沖的,當連接到檔案時是完全緩沖的。由于您沒有撰寫任何換行符,因此在任何一種模式下都不會自動重繪 緩沖區。當程式退出時,緩沖區會自動重繪 ,此時它會被寫入 FD 1 連接到的最后一個流。
要么關閉緩沖setvbuf(),要么在printf()呼叫之間顯式重繪 輸出。
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/fcntl.h>
#include <dirent.h>
void main(int argc, char* argv[]) {
int file1 = open("./text_try", O_CREAT | O_EXCL, 0666) //open file
printf("write to screen\n"); //print to screen
int oldOut = dup(1); //save screen FD
dup2(file1,1); //change output stream from screen to file
printf("write to file"); //print to file
fflush(stdout);
dup2(oldOut,1); //change output stream from file back screen
printf("write to screen"); //print to screen
fflush(stdout);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/400171.html
