Skip to content

Close file in C

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);

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 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);.

9 People found this is helpful