Linux文件IO接口之read函数使用

往一个文件写入数据,并读取数据

//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个!!!   (因为它都没得给你读取啊。。。。。)

	  所以利用读取函数的时候,都是“越界"读取,要求读取的数据大小,要比文件中数据的真实大小要大!!!! 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值