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 ?
Advertisement
Answer
The rule is to close the outermost level. Here the FILE object pointed to by f
contains the fd
file 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 the fd
file handle, but it will also release all the resources that were allocated by fopen
.
TL/DR: if you use fd= open(...);
to open a file, you should use close(fd);
to close it, but if you use f = fopen(...);
, then you should use fclose(f);
.