ptg10805159
148 StandardI/O Library Chapter 5
5.5 OpeningaStream
Thefopen,freopen,andfdopenfunctions open a standardI/O stream.
#include <stdio.h>
FILE *fopen(const char *restrictpathname,const char *restricttype);
FILE *freopen(const char *restrictpathname,const char *restricttype,
FILE *restrictfp);
FILE *fdopen(intfd,const char *type);
All three return: file pointer if OK,NULLon error
The differences in these three functions are as follows:
- Thefopenfunction opens a specified file.
2Thefreopenfunction opens a specified file on a specified stream, closing the
stream first if it is already open. If the stream previously had an orientation,
freopenclears it. This function is typically used to open a specified file as one
of the predefined streams: standardinput, standardoutput, or standarderror. - Thefdopenfunction takes an existing file descriptor,which we could obtain
from theopen,dup,dup2,fcntl,pipe,socket,socketpair,oraccept
functions, and associates a standardI/O stream with the descriptor.This
function is often used with descriptors that arereturned by the functions that
create pipes and network communication channels. Because these special types
of files cannot be opened with the standardI/Ofopenfunction, we have to call
the device-specific function to obtain a file descriptor,and then associate this
descriptor with a standardI/O stream usingfdopen.
Bothfopenandfreopenarepart of ISO C;fdopenis part of POSIX.1, since ISO C doesn’t
deal with file descriptors.
type Description open( 2 )Flags
rorrb open for reading O_RDONLY
worwb truncate to 0 length or create for writing O_WRONLY|O_CREAT|O_TRUNC
aorab append; open for writing at end of file, or O_WRONLY|O_CREAT|O_APPEND
create for writing
r+orr+borrb+ open for reading and writing O_RDWR
w+orw+borwb+ truncate to 0 length or create for reading and O_RDWR|O_CREAT|O_TRUNC
writing
a+ora+borab+ open or create for reading and writing at O_RDWR|O_CREAT|O_APPEND
end of file
Figure 5.2Thetypeargument for opening a standardI/O stream
ISO C specifies 15 values for thetypeargument, shown in Figure5.3. Using the
characterbas part of thetypeallows the standardI/O system to differentiate between a