利用wirte函数,往一个空文本中写入数据
//创建一个空文本文件
chenhai@linux:~/test$ touch a.txt
//编写程序,将字符串"hello"写入a.txt writefile.c
#include <stdio.h>
#include <sys/types.h> //调用open()函数所需的头文件
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h> //调用wirte()函数所需的头文件
int main()
{
int fd;
char buf[20]={"hello"}; //定义一个20字节大小的数组(数据缓冲区),用于存放要写入的数据
//打开文件
fd = open("/home/chenhai/test/a.txt",O_RDWR); //读写方式打开,返回一个文件描述符,后面根据这个文件描述符对文件进行操作
if(fd == -1)
{
printf("open a.txt faild\n");
}
else
{
printf("open a.txt ok\n");
}
//写入数据
int ret = write(fd,buf,20); //将数据从缓冲区中写入fd指向的文件,共写入20字节
if(ret == -1)
{
printf("write a.txt faild\n");
}
else
{
printf("write a.txt ok\n");
}
return 0;
}
那么,我们同样可以通过man手册来查看一下write的使用原理
chenhai@linux:~/test$ man 2 write
NAME
write - write to a file descriptor
写入一个文件的描述符
SYNOPSIS
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
参数一: 需要写入的设备
参数二: 需要写入的数据缓存区
参数三: 需要写入的数据大小
返回值: 成功 返回值写入的字节数
失败 -1 错误
小于用户请求的字节数 写入失败
一般使用write 函数进行开发时,我们都是根据数据的真实大小写入。
注意:使用write 函数的时候,他会根据用户的需求数据写入,假设
真实数据不够,那么write 会自己补充一些乱码数据!!!!!
例子:
char buf[1024]={"hello"}; //真实数据为5个字节
write(fd,buf,1024); //最后写入的是1024个字节, 1024 - 5 (个无效数据)