Basic File I/O
The following interfaces perform basic operations on files and on character I/O devices.
Table 5-1 Basic File I/O Interfaces
Interface Name | Purpose |
---|---|
|
Open a file for reading or writing. For more information, see the
|
|
Close a file descriptor. For more information, see the
|
|
Read from a file. For more information, see the
|
|
Write to a file. For more information, see the
|
|
Create a new file or rewrite an existing one. For more information, see the
|
|
Remove a directory entry. For more information, see the
|
|
Move read/write file pointer. For more information, see the
|
The following code sample demonstrates the use of the basic file I/O interface.
Example 5-1 Using the Basic File I/O Interface
#include <fcntl.h> #define MAXSIZE 256 main() { int fd; ssize_t n; char array[MAXSIZE]; fd = open ("/etc/motd", O_RDONLY); if (fd == -1) { perror ("open"); exit (1); } while ((n = read (fd, array, MAXSIZE)) > 0) if (write (1, array, n) != n) perror ("write"); if (n == -1) perror ("read"); close (fd); }
In this example, the read
and the write
interfaces both transfer the specified number of bytes, starting at the current offset into the file. The number of bytes transferred is returned. The end of a file is indicated on a read
by a return value of zero. For more information, see the
read
(2) and
write
(2) man pages.
When you are done reading or writing a file, call the close
interface. Do not call close
for a file descriptor that was not returned from a call to open
. For more information, see the
close
(2), and
open
(2) man pages.
File pointer offsets into an open file are changed by using read
, write
, or by calls to lseek
. For more information, see the
read
(2),
write
(2) and
lseek
(2) man pages.
The following example demonstrates the uses of lseek
.
off_t start, n; struct record rec; /* record current offset in start */ start = lseek (fd, 0L, SEEK_CUR); /* go back to start */ n = lseek (fd, -start, SEEK_SET); read (fd, &rec, sizeof (rec)); /* rewrite previous record */ n = lseek (fd, -sizeof (rec), SEEK_CUR); write (fd, (char *&rec, sizeof (rec));