Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close file in C

Tags:

c

file

linux

fclose

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 ?

like image 250
famedoro Avatar asked Feb 25 '26 19:02

famedoro


1 Answers

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

like image 95
Serge Ballesta Avatar answered Feb 28 '26 14:02

Serge Ballesta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!