Download Practical C Programming - International Research Institute MICA

Transcript
Unbuffered I/O
221
file_descriptor
is an integer that is used to identify the file for the read, write, and close calls.
If file descriptor is less than zero, an error occurred.
name
is the name of the file.
flags
are defined in the fcntl.h header file. Flags are described in Table 14-2.
mode
is the protection mode for the file. Normally, this is 0644 for most files.
Table 14-2: Open Flags
Flag
Meaning
O_RDONLY
Open for reading only
O_WRONLY
Open for writing only
O_RDWR
Open for reading and writing
O_APPEND
Append new data at the end of the file
O_CREAT
Create file (mode is required when this flag is
present)
O_TRUNC
If the file exists, truncate it to zero length
O_EXCL
Fail if file exists
O_BINARY
Open in binary mode (MS-DOS/Windows only)
O_TEXT
Open in text mode (MS-DOS/Windows only)
For example, to open the existing file data.txt in text mode for reading, we use
the following:
data_fd = open("data.txt", O_RDONLY);
The next example shows how to create a file called output.dat for writing only:
out_fd = open("output.dat", O_CREAT|O_WRONLY, 0644);
Notice that we combined flags using the or operator (|). This is a quick and easy
way of merging multiple flags.
When any program is initially run, three files are already opened. These are
described in Table 14-3.
Table 14-3: Standard Unbuffered Files
File number
Symbolic name
Description
0
STDIN_FILENO
Standard in
1
STDOUT_FILENO
Standard out
2
STDERR_FILENO
Standard err