Girişi bir dosyaya yeniden yönlendirmek için C'deki yönlendirmeleri kullanmaya çalışıyorum ve ardından standart çıktıyı ekrana yazdırmak üzere ayarlayın. Birisi bana bu kodun nesi yanlış olduğunu söyleyebilir mi? Bu hiç çalışacaktır önce gerekecekstandart çıktıyı c'ye yeniden yönlendiriyor ve daha sonra standart çıktıyı sıfırlıyor
#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;
}
Burada aynı sorunu çözmek için tamamen farklı bir yol var: http://stackoverflow.com/questions/584868/rerouting-stdin-and-stdout-from-c. – Sam