これが私のコードです:
#include<stdio.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
#include<unistd.h>
#include<errno.h>
int main(int argc,char *argv[])
{
int oldfd;
int newfd;
if(argc!=2)
{
printf("Usgae : %s file_name\n",argv[0]);
exit(0);
}
oldfd=open(argv[1],O_RDWR|O_APPEND,S_IRWXU); // Opening the file in Read/Write mode
if (-1 == oldfd)
{
perror("Error opening file");
exit(0);
}
close(1); // closing stdout
newfd=dup(oldfd); //Now this newfd holds the value 1
close(oldfd); //closing the oldfd
printf("\nStack Overflow"); //Now this printf will print content into the file as stdout closed already
close(newfd);// closing newfd
return 0;
}
私が実際にやろうとしているのは、write() システム コールの代わりに printf() を使用して、「スタック オーバーフロー」をファイルに出力することです。
コンテンツをファイルに出力していません。しかし、私が観察したことの1つは、コードを削除すると:
close(newfd)
期待どおりに内容をファイルに出力しています。しかし、私はその理由を理解できません。内容を印刷してから、newfd を閉じるだけです。
これの理由は何ですか?