I just learned about file descriptors and I was trying some code to understand the way it works. When writing the following program I was expecting that the first printf should be written to the console, then since I close the standard output and open a new file, I expected it to return the smallest file descriptor which is 1 (since it is available because I closed it previously). Then I was expecting the second printf to write to the file 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);
}
However, when I execute this, nothing is printed to the console but everything is printed to the file.txt, i.e.
file.txt
before closeafter close, the file descriptor is 1
Why is that?