Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: close FILE* - not filedescriptor [duplicate]

Tags:

c

fdopen

I wondered if it was possible to release a FILE wrapper, without closing the underlying file descriptor:

void stream_function( int fd ) {
    FILE * stream = fdopen( fd, "r");
    // Read from stream with fread / fscanf
    // then close the buffered stream object with the mythical
    // xclose( stream ) function, leaving the fd intact. 
    xclose( stream );  
}


int main( ) {
   int fd = open("filename" , flags);
   stream_function( fd );
   // Continue to use fd
   close( fd );
}
like image 416
user422005 Avatar asked Mar 25 '26 17:03

user422005


1 Answers

It's not. You can use dup2(fileno(f)) to keep a copy of the file descriptor, but fclose(f) inherently and always closes fileno(f).

In cases like yours where you're using fdopen to get the FILE * to begin with, however, you can dup2 the fd before passing it to fdopen. This protects the original fd from being closed at fclose time.

like image 77
R.. GitHub STOP HELPING ICE Avatar answered Mar 30 '26 11:03

R.. GitHub STOP HELPING ICE



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!