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 );
}
It's not. You can use
dup2(fileno(f))to keep a copy of the file descriptor, butfclose(f)inherently and always closesfileno(f).In cases like yours where you're using
fdopento get theFILE *to begin with, however, you candup2the fd before passing it tofdopen. This protects the original fd from being closed atfclosetime.