Tim
Tim

Reputation: 99536

what kinds of types can we specify in `fdopen()`, and which part of the type is valid?

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

Answers (1)

Barmar
Barmar

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 which fildes refers.

The Rationale section goes a little further:

The meanings of the mode arguments of fdopen() and fopen() differ. With fdopen(), open for write (w or w+) does not truncate, and append (a or a+) cannot create for writing. The mode argument formats that include a b are allowed for consistency with the ISO C standard function fopen(). The b 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 the O_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

Related Questions