曲径通幽论坛

标题: write [打印本页]

作者: beyes    时间: 2008-11-16 23:10
标题: write
NAME
       write -在一个文件描述符上执行写操作

包含文件
       #include <unistd.h>
       #include <sys/types.h>

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

      
描述
       write  向文件描述符 fd 所引用的文件中写入从 buf 开始的缓冲区中 count 字
       节的数据.  POSIX规定,当使用了write()之后再使用 read(),那么读取到的应 该
       是更新后的数据.  但请注意并不是所有的文件系统都是 POSIX兼容的.


返回值
       成功时,返回所写入的字节数(若为零则表示没有写入数据).  错误时返回-1,并
       置errno为相应值.  若count为零,对于普通文件无任何影响,但对特殊文件将产生
       不可预料的后果.
作者: beyes    时间: 2009-2-6 10:54
#include <unistd.h>
#include <stdlib.h>

int main()
{
        if ((write(1, "Here is some data\\n", 18)) != 18)
                write(2, "A write error has occurred on file descriptor 1\\n", 46);

        exit(0);
}
作者: beyes    时间: 2009-7-29 12:23
标题: 一个健壮版本的 write
write() 函数返回写入的实际字节数,这个数可能与要求的字节数不相同。大部分时间( 尤其是写入数据时 )这不会被当作是错误,但有时需要确保确实已写入了一定数量的字节。下面的 writen() 函数写入所要求数量的准确字节,除非发生错误或检测到文件末尾。

Code:
#include <errno.h>
#include <unistd.h>

ssize_t writen (int fd, const void *buf, size_t num)
{
    ssize_t    res;
    size_t    n;
    const char *ptr;

    n = num;
    ptr = buf;
    while (n > 0) {
        if ((res = write(fd, ptr, n)) <= 0) {
            if (errno == EINTR)           /*写入过程中发生了系统中断*/
                res = 0;
            else
                  return (-1);                /*写入错误*/
        }
        ptr += res;                               /*一次写入不到所希望的字节数,调整指针继续写*/
        n -= res;                                  /*n为剩下还没写的字节数*/
    }

    return (num);
}





欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2