编程接口指南

基本文件 I/O

以下接口针对文件和字符 I/O 设备执行基本操作。

表 5–1 基本文件 I/O 接口

接口名称 

目的 

open(2)

打开文件进行读取或写入 

close(2)

关闭文件描述符 

read(2)

从文件中读取 

write(2)

向文件中写入 

creat(2)

创建新文件或重写现有文件 

unlink(2)

删除目录项 

lseek(2)

移动读/写文件指针 

以下代码样例说明了基本文件 I/O 接口用法。read(2)write(2) 都从文件当前偏移位置开始传送不超过指定数量的字节。返回实际传送的字节数。read(2) 返回零时指示已到达文件结尾。


示例 5–1 基本文件 I/O 接口

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

}

完成读取或写入文件后,应始终调用 close(2)。不要针对不是从调用 open(2) 返回的文件描述符调用 close(2)

使用 read(2)write(2),或者调用 lseek(2) 可以改变已打开文件的文件指针偏移。以下示例说明了 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));