Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 5.5 Opening a Stream 149


text file and a binary file. Since the UNIX kernel doesn’t differentiate between these
types of files, specifying the characterbas part of thetypehas no effect.
Withfdopen,the meanings of thetypeargument differ slightly.The descriptor has
already been opened, so opening for writing does not truncate the file. (If the descriptor
was created by theopen function, for example, and the file already existed, the
O_TRUNCflag would control whether the file was truncated. Thefdopenfunction
cannot simply truncate any file it opens for writing.) Also, the standardI/O append
mode cannot create the file (since the file has to exist if a descriptor refers to it).
When a file is opened with a type of append, each write will take place at the then
current end of file. If multiple processes open the same file with the standardI/O
append mode, the data from each process will be correctly written to the file.

Versions offopenfrom Berkeley before4.4BSD and the simple version shown on page 177 of
Kernighan and Ritchie[ 1988 ]do not handle the append mode correctly.These versions do an
lseekto the end of file when the stream is opened. To correctly support the append mode
when multiple processes areinvolved, the file must be opened with theO_APPENDflag, which
we discussed in Section 3.3. Doing anlseekbeforeeach write won’t work either, as we
discussed in Section 3.11.

When a file is opened for reading and writing (the plus sign in thetype), two
restrictions apply.
•Output cannot be directly followed by input without an interveningfflush,
fseek,fsetpos,orrewind.
•Input cannot be directly followed by output without an interveningfseek,
fsetpos,orrewind, or an input operation that encounters an end of file.
We can summarize the six ways to open a stream from Figure5.2 in Figure5.3.

Restriction rwar+ w+ a+
file must already exist ••
previous contents of file discarded • •
stream can be read • •••
stream can be written •••••
stream can be written only at end ••

Figure 5.3 Six ways to open a standardI/O stream

Note that if a new file is created by specifying atypeof eitherwora, we are not able to
specify the file’s access permission bits, as we wereable to do with theopenfunction
and thecreatfunction in Chapter 3. POSIX.1 requires implementations to create the
file with the following permissions bit set:
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH
Recall from Section 4.8, however,that we can restrict these permissions by adjusting our
umaskvalue.
By default, the stream that is opened is fully buffered, unless it refers to a terminal
device, in which case it is line buffered. Once the stream is opened, but before we do
Free download pdf