stdoutをファイルにリダイレクトしてから、Cで元のファイルに復元しようとしていますが、次の奇妙な問題に直面しています。次のコードは
in stdout
in stdout
、stdoutとin file
それぞれのファイルに正常に書き込まれます。
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#define STDOUT 1
int main(int argc, char* argv[]){
printf("in stdout \n");
int old_out = dup(STDOUT);
close(STDOUT);
int fd = open("./redirected",O_CREAT|O_RDWR|O_TRUNC,0777);
printf("in file \n");
close(fd);
dup(old_out);
printf("in stdout\n");
return EXIT_SUCCESS;
}
ただし、メイン関数の最初の行を削除します。
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#define STDOUT 1
int main(int argc, char* argv[]){
int old_out = dup(STDOUT);
close(STDOUT);
int fd = open("./redirected",O_CREAT|O_RDWR|O_TRUNC,0777);
printf("in file \n");
close(fd);
dup(old_out);
printf("in stdout\n");
return EXIT_SUCCESS;
}
stdout
in file
in stdout
に書き込まれ、ファイルには何も書き込まれません。これはどうして起こったのだろうか?助けてくれてありがとう。