我試圖在C中使用重定向將輸入重定向到一個文件,然後將標準輸出設置回打印到屏幕。有人能告訴我這段代碼有什麼問題嗎?你必須在c中重定向標準輸出,然後重置標準輸出
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char** argv) {
//create file "test" if it doesn't exist and open for writing setting permissions to 777
int file = open("test", O_CREAT | O_WRONLY, 0777);
//create another file handle for output
int current_out = dup(1);
printf("this will be printed to the screen\n");
if(dup2(file, 1) < 0) {
fprintf(stderr, "couldn't redirect output\n");
return 1;
}
printf("this will be printed to the file\n");
if(dup2(current_out, file) < 0) {
fprintf(stderr, "couldn't reset output\n");
return 1;
}
printf("and this will be printed to the screen again\n");
return 0;
}
有一個完全不同的方法來解決這個相同的問題在這裏:http://stackoverflow.com/questions/584868/rerouting-stdin-and-stdout-from-c。 – Sam