Tôi đang cố sử dụng chuyển hướng trong C để chuyển hướng đầu vào đến một tệp và sau đó đặt đầu ra chuẩn thành in ra màn hình. Ai đó có thể cho tôi biết những gì sai với mã này?chuyển hướng đầu ra tiêu chuẩn bằng c sau đó đặt lại đầu ra tiêu chuẩn
#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;
}
Có cách hoàn toàn khác để giải quyết vấn đề tương tự ở đây: http://stackoverflow.com/questions/584868/rerouting-stdin-and-stdout-from-c. – Sam