Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

144 StandardI/O Library Chapter 5


StandardI/O file streams can be used with both single-byte and multibyte (‘‘wide’’)
character sets. Astream’s orientation determines whether the characters that areread
and written aresingle byte or multibyte. Initially,when a stream is created, it has no
orientation. Ifamultibyte I/O function (see<wchar.h>) is used on a stream without
orientation, the stream’s orientation is set to wide oriented. If a byte I/O function is
used on a stream without orientation, the stream’s orientation is set to byte oriented.
Only two functions can change the orientation once set. Thefreopen function
(discussed shortly) will clear a stream’s orientation; thefwidefunction can be used to
set a stream’s orientation.
#include <stdio.h>
#include <wchar.h>
int fwide(FILE *fp,intmode);
Returns: positive if stream is wide oriented,
negative if stream is byte oriented,
or 0 if stream has no orientation
Thefwide function performs different tasks, depending on the value of themode
argument.

•Ifthemodeargument is negative,fwidewill try to make the specified stream
byte oriented.
•Ifthemodeargument is positive,fwidewill try to make the specified stream
wide oriented.
•Ifthemodeargument is zero,fwidewill not try to set the orientation, but will
still return a value identifying the stream’s orientation.

Note thatfwidewill not change the orientation of a stream that is already oriented.
Also note that there is no error return. Consider what would happen if the stream is
invalid. The only recourse we have is to clearerrnobeforecallingfwideand check
the value oferrnowhen we return. Throughout the rest of this book, we will deal only
with byte-oriented streams.
When we open a stream, the standardI/O functionfopen(Section 5.5) returns a
pointer to aFILEobject. This object is normally a structurethat contains all the
information required by the standardI/O library to manage the stream: the file
descriptor used for actual I/O, a pointer to a buffer for the stream, the size of the buffer,
acount of the number of characters currently in the buffer, an error flag, and the like.
Application softwareshould never need to examine aFILEobject. Toreference the
stream, we pass itsFILEpointer as an argument to each standardI/O function.
Throughout this text, we’ll refer to a pointer to aFILEobject, the typeFILE *, as afile
pointer.
Throughout this chapter, we describe the standardI/O library in the context of a
UNIX system. As we mentioned, this library has been ported to a wide variety of other
operating systems. To provide some insight about how this library can be
implemented, we will talk about its typical implementation on a UNIX system.
Free download pdf