Is there a way to get the FILE
structure from the descriptor that is C99 compliant?
If by "C99 compliant" you mean relying only on features of the C standard library specified by C99 then no. But that's ok, because there is no way to get or use a file descriptor in the first place if you rely only on the standard library of C99. Streams, managed via C FILE
objects, are the only representation of files defined by C99.
On the other hand, if you're talking about limiting yourself to the syntax and semantics of C99, but not necessarily to standard library functions it specifies, then yes: use fdopen()
. It serves exactly the purpose you describe.
Since you appear to be using gcc, perhaps the question arises because you want to compile with the -std=c99
option to disable language extensions, and you find that this also disables (or at least, does not enable) declaration of some functions, including fdopen()
. This is because the -std
option affects the default values of some of the standard feature test macros. The documentation for fdopen()
says that it requires one of a variety feature-test macros: either _POSIX_C_SOURCE
with a value greater than 0, or _XOPEN_SOURCE
, or _POSIX_SOURCE
. With -std=gnu99
you get settings of all of those that serve the purpose, but with -std=c99
you don't get definitions of any of them that will do the job.
If you want all the library features of the latest version of POSIX (that are provided by your glibc) then you should ensure that _POSIX_C_SOURCE
is defined with value 200809L
(as of POSIX.1-2017). Since such dependence is a characteristic of your source code, not of the compilation conditions, you should put an appropriate macro definition at the very beginning of your source files (that is, don't depend on compilation options for this). For example:
#ifdef _POSIX_C_SOURCE
#undef _POSIX_C_SOURCE
#endif
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <fcntl.h>
// ...
The macro should be defined before any headers are #include
d.
You should then be able to compile with gcc -std=c99
and also have a declaration of fdopen()
.