一、函数介绍
write 函数在头文件“#include <unistd.h>”中。
函数原型为 ssize_t write(int fd,const void *buf,size_t count)
参数 fd,使用 open 函数打开文件之后返回的句柄。
参数*buf,需要写入的数据。
参数 count,将参数*buf 中最多 count 个字节写入文件中。
返回值为 ssize 类型,出错会返回-1,其它数值表示实际写入的字节数。
二、例程
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
main()
{
int fd;
ssize_t fw;
char *write_string = "Test Function!!";
char *path = "/bin/test";
if((fd=open(path, O_RDWR|O_CREAT, 0777)) == -1)
{
perror("open");
}
else
{
printf("successful create test\n");
}
fw = write(fd, write_string, strlen(write_string);
if(fw == -1)
{
perror("write");
}
else
{
printf("write Function OK!\n");
}
close(fd);
}
在末尾记得 close....
三、运行效果
创建且写入成功
目录下的test文件
进入看看里面的内容