Cosinus
Cosinus

Reputation: 659

Can I close a FILE without closing the fd?

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

Answers (2)

Deduplicator
Deduplicator

Reputation: 45664

If you want to get the file descriptor and disassociate it from the the FILE*, there is one supported way:

  1. Get the file descriptor with fileno(). (POSIX)
  2. Duplicate it using dup(). (POSIX)
  3. Close the FILE the normal way with fclose(). (c)

Now you only have a file descriptor.

Upvotes: 5

GooseDeveloper
GooseDeveloper

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 by fp (writing any buffered output data using fflush(3)) and closes the underlying file descriptor.

Upvotes: 0

Related Questions