Reputation: 659
I've opened a FILE *f
with fdopen(fd, "w+")
and I would like to keep the fd
open after closing with fclose(f)
.
Is there an elegant way to do that?
Can I simply call fflush(f); free(f);
or is that dangerous?
Or is there a way to change the internal fd
to an invalid value -1
so that fd
cannot be closed by fclose()
?
Upvotes: 4
Views: 1335
Reputation: 45664
If you want to get the file descriptor and disassociate it from the the FILE*
, there is one supported way:
fileno()
. (POSIX)dup()
. (POSIX)FILE
the normal way with fclose()
. (c)Now you only have a file descriptor.
Upvotes: 5
Reputation: 137
If you'd really like to use a FILE
object rather than a file descriptor, you needn't worry about close()
ing the file descriptor: fclose()
does this for you. Also, if performance is important, you should worry about all of the fdopen()
and wrapped system calls defined in f*()
standard I/O functions. Big thanks to all the comments!
Also see the fclose man page:
The
fclose()
function flushes the stream pointed to byfp
(writing any buffered output data usingfflush(3)
) and closes the underlying file descriptor.
Upvotes: 0