文档介绍:Standard I/O Library
Streams and FILE objects
Three types of buffering
Open a stream
read/write a stream
Positioning a stream
Formatted I/O
Temporary files
Streams and FILE Objects
Unbuffered I/O
File Descriptor driven - CH 3
3 pre-defined descriptors
STDIN_FILENO
STDOUT_FILENO
STDERR_FILENO
Some system calls
open
creat
lseek
read
write
尼龙棒有机玻璃板 p://
Streams and FILE Objects
Standard I/O
File stream driven - FILE*
Associate a file with a stream and operate on the stream
3 pre-defined streams
stdin
stdout
stderr
Buffering
Goal of buffering is to minimize the number of read and write calls.
Three types of buffering
Fully buffered – Block Buffered
Line buffered
Unbuffered
ANSI C requirements
stderr must never be fully buffered
stdin and stdout are fully buffered if the device they use is not interactive
Buffering
On most UNIX/Linux systems
stderr is always unbuffered
Streams for terminals are line buffered
All other streams are fully buffered
Setting Buffer Type
setbuf
void setbuf(FILE *stream, char *buf);
Enable or disable buffering on a stream
If buf is NULL buffering is disabled
Buffer must be of size BUFSIZ as defined in <>
Setting Buffer Type
setvbuf
int setvbuf(FILE *stream, char *buf, int mode , size_t size);
Can set all 3 types of buffering depending on value of mode
_IOFBF - Fully buffered
_IOLBF - Line buffered
_IONBF - Non buffered
If buf is NULL, system will create its own buffer automatically
buf is ignored if mode is _IONBF
setbuf(fp, NULL) is the same assetvbuf(fp, buf, _IONBF, size)
Opening a Stream
FILE *fopen(const char *path, const char *mode);
FILE *freopen(const char *path, const char *mode, FILE *stream);
FILE *fdopen(int fildes, const char *mode);
fopen opens the file given by path.
freopen opens a file on a specified stream, closing the stream first if its already open
fdopen opens a stream from a file descriptor. Useful for streams that don’t have a regular file such a pipes
Opening a Stream
mode
r or rb
w or wb
a or