← 返回首页
Linux高级程序设计(二十)
发表时间:2021-11-09 22:49:46
write函数

1.write

write函数是Linux下不带缓存的文件I/O操作函数之一,所谓的不带缓存是指一个函数只调用系统中的一个函数。另外还有open、read、lseek、close,它们虽然不是ANSI C的组成部分,但是POSIX的组成部分。

#include <unistd.h>

//write()会把参数buf所指的内存写入count个字节到参数fd所指的文件内
ssize_t (int fd, const void * buf, size_t count); 

函数返回值分为下面几种情况: - 如果读取成功,则返回实际读到的字节数。这里又有两种情况:一是如果在读完count要求字节之前已经到达文件的末尾,那么实际返回的字节数将 小于count值,但是仍然大于0;二是在读完count要求字节之前,仍然没有到达文件的末尾,这是实际返回的字节数等于要求的count值。 - 如果读取时已经到达文件的末尾,则返回0。 - 如果出错,则返回-1。

实例: 向终端写入字符串。

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
//#include <unistd.h>
//windows下无法打开源文件"unistd.h"采用以下方式解决
#ifndef _UNISTD_H
#define _UNISTD_H
#include <io.h>
#include <process.h>
#endif

int main(int argc, char const *argv[])
{
    //向终端写入字符串。
    if (write(1, "hello,world!", 12) == -1)
    {
        perror("fail to write file:");
        return -1;
    }
    return 0;
}

运行结果:

hello,world!

实例: 向文件写入字符串。

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
//#include <unistd.h>
//windows下无法打开源文件"unistd.h"采用以下方式解决
#ifndef _UNISTD_H
#define _UNISTD_H
#include <io.h>
#include <process.h>
#endif

int main(int argc, char const *argv[])
{
    int fd;
    int bytes;
    //打开文件
    fd = open("test.txt", O_CREAT | O_WRONLY | O_TRUNC, 0664);
    if (fd == -1)
    {
        perror("fail to open file:");
        return -1;
    }
    //向文件写入字符串。
    if ((bytes = write(fd, "hello,world!\n", 13)) == -1)
    {
        perror("fail to write file:");
        return -1;
    }
    printf("bytes=%d", bytes);
    return 0;
}

测试运行:

bytes=13