1.write
用于向一个已打开的文件写入特定的内容。
2.头文件
#include
3.函数原型
ssize_t write(int fd, const void *buf, size_t count);
4.参数
fd:表示要操作文件的文件描述符。
buf:表示要写入数据存放的位置(缓冲区地址)。
count:表示要写入的字节数。
5.返回值
若写入成功,则返回写入的字节数;若失败,返回-1。
6.示例:(打开test文件,写入特定内容)
#include
#include
#include
#include
#include
#include
int main()
{
char buf[30] = "HELLO WORLD!!!\n";
int fd = open("./test", O_RDWR | O_CREAT | O_TRUNC, 0666);
if (fd < 0) {
printf("error: test open\n");
return -1;
}
if ( write(fd, buf, strlen(buf)) < 0 ) {
printf("error: test write\n");
return -1;
}
return 0;
}
7.编译运行并查看测试结果
$ cat test //程序向test写入内容,所以执行后通过cat查看test文件内容
HELLO WORLD!!!