0

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.

Tim
  • 1
  • 141
  • 372
  • 590
  • Possible duplicate of [What's the difference between a file descriptor and file pointer?](https://stackoverflow.com/q/2423628/608639) – jww Aug 31 '18 at 05:56

1 Answers1

1

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks. What happens if the file descriptor is open for writing and you use mode r in fopen(), and if it's open for reading and you use mode w in fopen()? – Tim Aug 30 '18 at 19:37
  • The results are unspecified, and likely depends on the device driver. – Barmar Aug 30 '18 at 19:39
  • 1
    When the specification says that you **shall** do something, and you don't do it, the consequeces are undefined. – Barmar Aug 30 '18 at 19:40