Under Linux I use this code to redirect stdout and stderr on a file, as shown in the code the file is opened using fopen(f) and is it closed using close(fd).
int fd;
FILE *f;
f = fopen("test.txt", "rb+");
fd = fileno(f);
dup2(fd,STDOUT_FILENO);
dup2(fd,STDERR_FILENO);
close(fd);
My question is whether the close(fd) statement closes all file descriptors, or is it necessary to use fclose(f) as well ?
The rule is to close the outermost level. Here the FILE object pointed to by
fcontains thefdfile handle but also internal data like a possible buffer and various pointers to it.When you use
close(fd), you free the kernel structures related to the file, but all the data structures provided by the standard library are not released. On the other hand,fclose(f)will internally close thefdfile handle, but it will also release all the resources that were allocated byfopen.TL/DR: if you use
fd= open(...);to open a file, you should useclose(fd);to close it, but if you usef = fopen(...);, then you should usefclose(f);.