By using fdopen(), fileno() it’s possible to open streams with existing file descriptors. However the proper way to close a file, once you’ve opened it with a stream is to fclose() the FILE pointer. How can one close the stream, but retain the open file descriptor?
This behaviour is akin to calling fflush() and then fileno(), and then never using the FILE pointer again, except in closing. An additional concern is that if you then fdopen() again, there are now multiple FILE pointers, and you can only close one of them.
If you’re on a POSIXy system (which I assume you are, since you have
fileno()), you can usedup()to clone the file descriptor:Or you can hand
fdopen()a duplicate file descriptor:Either way, the other copy of the fd won’t close with the
FILE *. However, keep in mind the location pointer is shared, so be careful if you are using both at the same time. Also, anyfcntl()locks held on the original fd will be released when you close the copy.