Linux中write函数

功能:

     向文件中写入数据

头文件:

     #include  <unistd.h>

原型:

     ssize_t

write(int fd, const void *buf, size_t count);

参数:

     fd:         文件描述符

    buf:      存放要写入的数据的缓冲区首地址

     count:   想要写入的字节数

返回值:

     >=0:成功写入的字节数,0表示什么都没写入

     -1:   写入失败,并设置全局变量errno

例:

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

#include <strings.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <fcntl.h>

int main(int argc, char *argv[])
{
if(argc < 2) {
fprintf(stderr,“Usage: %s \n”, argv[0]);
return -1;
}
int fd = 0;
if (0 > (fd = open(argv[1], O_WRONLY|O_CREAT|O_TRUNC, 0666)))
{
perror(“open”);
return -1;
}
char buf[100] = “hello world!”;
int ret;
if (strlen(buf) != write(fd, buf, strlen(buf)))
{
perror(“write”);
return-1;
}
printf(“Write file successfully!\n”);
close(fd);
return0;
}

注意:write第三个参数表示想要写入的字节数,返回值表示实际写入的字节数,-1表示出错。如果要查看真正写入的字节数需要看返回值。比如套接字文件或者管道文件,有时候不能一次性把整个buf全部写入文件,此时需要循环写入。

例:

ssize_t mywrite(int fd, const void *buf, size_t count)
{
ssize_t size = 0;
int ret = 0;
while (size < count)
{
ret = write(fd, buf+size, count-size);
size += ret;
}
return size;
}

上述函数mywrite的功能是保证能够成功写入count字节,mywrite的参数与write函数一样。size表示已经写入的字节数,当成功写入的字节数小于想要写入的字节数时,循环往文件中写,从buf偏移size处开始把剩下的内容写入文件,直到size等于count跳出循环。

当写入的文件时套接字或者管道文件时,有一个发送缓冲区,如果缓冲区已满,此时发送阻塞,这就是写阻塞。如果设置为非阻塞模式O_NONBLOCK,缓冲区写满后,返回-1,错误原因Resource temporarily unavailable。

当写入的文件时套接字或者管道文件时,
如果读端关闭,写端还在向对端写入数据时,此时会产生管道破裂信号SIGPIPE,导致程序终止。如果写进程没有报任何错误就结束,很有可能就是管道破裂造成,可以使用signal函数去捕捉该信号,判断错误原因

例: signal(SIGNAL, handler);


版权声明:本文为qq_37710269原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。