How to get a FILE pointer from a file descriptor and how to get a file descriptor from a FILE pointer in C on Linux?

I would like to open files by open() directly. But how to get a FILE pointer from a file descriptor in C on Linux? And how to do the reverse direction: get a file descriptor from a FILE pointer?

Get a FILE pointer from a file descriptor (e.g. fd) in C on Linux:

FILE *file = fdopen(fd, "w");

Here, the second parameter is the modes which you can choose those for fopen.

More details can be found in the man page of fdopen: fdopen manual .

Get the file descriptor from a FILE pointer (e.g. file) in C on Linux:

int fd = fileno(file);

More details can be found in the man page of fileno: fileno manual .

Answered by Eric Z Ma.

Eric Z Ma

Eric is a father and systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *