往一个文件写入数据,并读取数据
//readfile.c
#include <stdio.h>
#include <sys/types.h> //调用open()函数所需的头文件
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h> //write , read
int main()
{
int fd;
char buf[10]={"hello"};
char str[20]={0};
//open file
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");
}
//write file
int ret = write(fd,buf,10);
if(ret == -1)
{
printf("write a.txt faild\n");
}
else
{
printf("write a.txt ok\n");
}
#if 1
close(fd);
fd = open("/home/chenhai/test/a.txt",O_RDWR);
if(fd == -1)
{
printf("open faild !!\n");
}
else
{
printf("open success again\n");
}
#endif
int val = read(fd,str,20);
if(val == -1)
{
printf("read faild!!!\n");
}
else
{
printf("read ok,the value is: %s\n",str);
}
return 0;
}
通过man手册查看read的使用方法
NAME
read - read from a file descriptor
读 从 文件描述符
SYNOPSIS
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
参数一:需要读取的文件描述符
参数二:读取后的数据缓存地址
参数三:需要读取的数据大小
返回值: 成功 返回读取到字节数
0 已经读到文件的末尾了
-1 读取错误
注意: 读函数,他只会根据文本中的内容去读取。 假设文本中只有10 个字节的数据,
用户要求读取100个字节的数据,那么最终只会读到 10个!!! (因为它都没得给你读取啊。。。。。)
所以利用读取函数的时候,都是“越界"读取,要求读取的数据大小,要比文件中数据的真实大小要大!!!!