Skip to Content
UNIX Filesystems: Evolution, Design, and Implementation
book

UNIX Filesystems: Evolution, Design, and Implementation

by Steve D. Pate
January 2003
Intermediate to advanced content levelIntermediate to advanced
480 pages
13h 22m
English
Wiley
Content preview from UNIX Filesystems: Evolution, Design, and Implementation

Opening and Closing a Stream

The fopen() and fclose() library routines can be called to open and close a file stream:

#include <stdio.h>

FILE *fopen(const char *filename, const char *mode);
int fclose(FILE *stream);

The mode argument points to a string that starts with one of the following sequences. Note that these sequences are part of the ANSI C standard.

r, rb. Open the file for reading.

w, wb. Truncate the file to zero length or, if the file does not exist, create a new file and open it for writing.

a, ab. Append to the file. If the file does not exist, it is first created.

r+, rb+, r+b. Open the file for update (reading and writing).

w+, wb+, w+b. Truncate the file to zero length or, if the file does not exist, create a new file and open it for update (reading and writing).

a+, ab+, a+b. Append to the file. If the file does not exist it is created and opened for update (reading and writing). Writing will start at the end of file.

Internally, the standard I/O library will map these flags onto the corresponding flags to be passed to the open() system call. For example, r will map to O_RDONLY, r+ will map to O_RDWR and so on. The process followed when opening a stream is shown in Figure 4.1.

The following example shows the effects of some of the library routines on the FILE structure:

images

Figure 4.1 Opening a file through the stdio library.

1 #include <stdio.h> 2 3 main() 4 { ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Design and Implementation of the FreeBSD Operating System, 2nd Edition

Design and Implementation of the FreeBSD Operating System, 2nd Edition

Marshall Kirk McKusick, George V. Neville-Neil, Robert N.M. Watson

Publisher Resources

ISBN: 9780471456759Purchase book