System Interface Guide

Basic File I/O

The functions listed in Table 5-1 perform basic operations on files:

Table 5-1 Basic File I/O Functions

Function Name 

Purpose 

open(2)

Open a file for reading or writing 

close(2)

Close a file descriptor 

read(2)

Read from a file 

write(2)

Write to a file 

creat(2)

Create a new file or rewrite an existing one 

unlink(2)

Remove a directory entry 

lseek(2)

Move read/write file pointer 

The following code sample demonstrates the use of the basic file I/O interface. read(2) and write(2) both transfer no more than the specified number of bytes, starting at the current offset into the file. The number of bytes actually transferred is returned. The end of a file is indicated, on a read(2), by a return value of zero.


Example 5-1

#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);
}

Always close(2) a file when you are done reading or writing it, but never close(2) a file descriptor that you did not open(2).

Offset into an open file are changed by read(2)s, write(2)s, or by calls to lseek(2). Some examples of using lseek(2) are:


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));