3.8 write函数-文件数据写

来源:互联网 发布:哪些大学有云计算专业 编辑:程序博客网 时间:2024/05/19 18:14

write函数用于向打开的文件写入数据。函数原型如下:

#include <unistd.h>ssize_t write(int filedes, const void *buf, size_t nbtyes);

返回值:如果写成功则返回实际写入的字节数,若出错则返回-1。

参数:

1、filedes 文件标识符,由调用open函数从内核获得。

2、*buf 待写入数据的缓冲区地址。

3、nbytes 需要写入文件的数据字节数。


write函数与read函数基本相同,但write函数除非出错,否则返回值等于要写的字节数nbtyes

在调用write函数之前要做两件事:

1、用open函数打开文件,获得文件标识符和写操作权;

2、要调用lseek定位要写入数据的位置。


实例 x3.8.1.c

#include <fcntl.h>#include <unistd.h>#include <stdio.h>#define BUFFSIZE 256int main(void){    char        pathname[] = "/tmp/myfile"; /*文件路径*/    int         fileid;                     /*文件标识符*/    off_t       f_offset;                   /*偏移量*/    ssize_t     nwrite;                      /*实际写入的字节数*/    char        buf[BUFFSIZE] = {'a','b','c','d','e'}; /*数据缓冲器*/    size_t      nbytes;                     /*要写的字节数*//*打开文件,获取文件标识符*/    fileid = open(pathname, O_RDWR | O_CREAT);    if (fileid == -1) {        printf("open error for %s\n", pathname);        return 1;    }/*定位文件写入位置(当前文件偏移量)*/    f_offset = lseek(fileid, 3, SEEK_SET);    if (f_offset == -1) {        printf("lseek error for %s\n", pathname);        return 2;    } /*将数据写入文件*/    nbytes = 5;                           /*设置要写入的字节数*/    nwrite = write(fileid, buf, nbytes);    /*调用write函数写入数据*/    if (nwrite == -1) {                    /*判断写操作是否成功*/        printf("write error for %s\n", pathname);        return 3;     }    close(fileid);    return 0;}

编译与执行:

[root@localhost unixc]# echo "0123456789" > /tmp/myfile
[root@localhost unixc]# cc x.3.8.1.c
[root@localhost unixc]# ./a.out
[root@localhost unixc]# cat /tmp/myfile
012abcde89
[root@localhost unixc]#

从执行结果看,“abcde”覆盖了原来的“34567”。可见write操作是覆盖式的写入新数据,而不是从指定位置插入新数据,除非文件当前偏移量位于文件结尾或者超出文件结尾位置。

超出文件结尾的位置是可以的,会跳过超出字节数写入新数据,同时留下一个所谓的文件空洞(不包含数据的一个文件段)。

原创粉丝点击