我刚刚学习了文件描述符,我正在try 一些代码来理解它的工作方式.在编写下面的程序时,我希望第一个printf应该写入控制台,然后,因为我关闭了标准输出并打开了一个新文件,所以我希望它返回最小的文件描述符1(因为它是可用的,因为我之前关闭了它).然后,我期待第二个printf写入文件file.txt.
#include<fcntl.h>
#include<stdio.h>
#include<unistd.h>
int main()
{
printf("before close");
close(1);
int x1 = open("./file.txt", O_RDWR);
printf("after close, the file descriptor is %d\n", x1);
}
但是,当我执行此命令时,控制台不会打印任何内容,但所有内容都会打印到文件.txt,即
file.txt个
before closeafter close, the file descriptor is 1
为什么会这样呢?