Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close a FILE pointer without closing the underlying file descriptor

Tags:

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.

like image 711
Matt Joiner Avatar asked Oct 21 '09 22:10

Matt Joiner


People also ask

Which is the correct way to close a file with file pointer?

The fclose() function is used to close an already opened file. A file must be closed as soon as all operations on it have been completed. This would close the file associated with the file pointer.

Does Fclose close file descriptor?

The fclose() function flushes the stream pointed to by stream (writing any buffered output data using fflush(3)) and closes the underlying file descriptor.

What happens to file descriptor after close?

close() closes a file descriptor, so that it no longer refers to any file and may be reused. Any record locks (see fcntl(2)) held on the file it was associated with, and owned by the process, are removed (regardless of the file descriptor that was used to obtain the lock).

Does closing a file reset the file pointer?

It will reset. If you want to save the position, store in a variable by calling tellg on the stream (before you close the stream).


2 Answers

If you're on a POSIXy system (which I assume you are, since you have fileno()), you can use dup() to clone the file descriptor:

int newfd = dup(fileno(stream));
fclose(stream);

Or you can hand fdopen() a duplicate file descriptor:

FILE *stream = fdopen(dup(fd), "r");

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, any fcntl() locks held on the original fd will be released when you close the copy.

like image 88
bdonlan Avatar answered Oct 25 '22 14:10

bdonlan


If everything else fails, dup(2) could help.

like image 22
ndim Avatar answered Oct 25 '22 14:10

ndim