Reputation: 99536
APUE says
With fdopen, the meanings of the type argument differ slightly.
The descriptor has already been opened, so opening for writing does not truncate the file. (If the descriptor was created by the open function, for example, and the file already existed, the O_TRUNC flag would control whether the file was truncated. The fdopen function cannot simply truncate any file it opens for writing.)
Also, the standard I/O append mode cannot create the file (since the file has to exist if a descriptor refers to it).
In general, when we call fdopen()
on a file descriptor returned from open()
,
what kinds of types can we specify in fdopen()
?
Must the type specified in fdopen()
be exactly the same as the mode specified in open()
?
Can the type specified in fdopen()
be a subset, superset, or neither subset nor superset of the mode specified in open()
?
If there is no restriction on the types specified in fdopen()
with respect to the mode specified in the previous open()
, which part of the type specified in fdopen()
is valid, and which part isn't (i.e. is ignored)?
Thanks.
Upvotes: 0
Views: 196
Reputation: 782310
POSIX specifies:
The application shall ensure that the mode of the stream as expressed by the
mode
argument is allowed by the file access mode of the open file description to whichfildes
refers.
The Rationale section goes a little further:
The meanings of the
mode
arguments offdopen()
andfopen()
differ. Withfdopen()
, open for write (w
orw+
) does not truncate, and append (a
ora+
) cannot create for writing. Themode
argument formats that include ab
are allowed for consistency with the ISO C standard functionfopen()
. Theb
has no effect on the resulting stream. Although not explicitly required by this volume of IEEE Std 1003.1-2001, a good implementation of append (a
) mode would cause theO_APPEND
flag to be set.
Since file descriptors can be opened in a wide variety of ways (open()
, socket()
, etc.), and there can be custom device drivers that have different restrictions, it's not really possible to provide a general specification of the relationship between the open()
mode and the fdopen()
mode.
But it should be pretty safe to assume that if the file descriptor is open for writing, you should be able to use mode w
, and if it's open for reading you can use mode r
.
Upvotes: 1