文件读取操作

本文介绍了C语言中read()和write()函数用于文件读写的使用方法,通过示例代码展示了如何将字符串写入文件以及读取文件内容。在遇到读取文件为空的问题时,提出了两种解决方案:重新打开文件或移动文件指针到开头。通过应用这些方法,成功读取了文件内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

读取文件手册

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA6ZW_56m6Ou-8ieWklemGiQ==,size_20,color_FFFFFF,t_70,g_se,x_16

 

函数定义:ssize_t read(int fd, void * buf, size_t count);

函数说明:read()会把参数fd所指的文件传送count 个字节到buf 指针所指的内存中。

返回值:返回值为实际读取到的字节数, 如果返回0, 表示已到达文件尾或是无可读取的数据。若参数count 为0, 则read()不会有作用并返回0。另外,以下情况返回值小于count。

代码实现 

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main()
{
	int fd;
	char *buf = "chenglong henshuai?";

	fd = open("./file1",O_RDWR);
	
	if(fd == -1){
		printf("open file1 failed\n");
		fd = open("./file1",O_RDWR|O_CREAT,0600);
		if(fd > 0){
			printf("create file1\n");
		}
	}
	printf("fd = %d\n",fd);
	
	int n_write = write(fd,buf,strlen(buf));
//	write(fd,buf,sizeof(buf));
	
	if(n_write != -1){    //判断是否写入成功,失败返回-1
		printf("write %d byte to file1\n",n_write);
	}	

	char *readBuf;    //野指针
	readBuf = (char *)malloc(sizeof(char )*n_write + 1);	//读取开辟写入+1的大小,强转成char型指针

	int n_read = read(fd,readBuf,n_write);
	
	printf("read %d,context:%s\n",n_read,readBuf);
	
	close(fd);

	return 0;
}
fd = 3
write 19 byte to file1
read 0,context:

问题发现:无法读取文件(光标的问题)

光标位置在chenglong henshuai?问号后面,读取的是光标后面的空内容。

解决方法:1.重新打开文件(老土法)   2.光标移动到头头(好方法)

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main()
{
	int fd;
	char *buf = "chenglong henshuai?";

	fd = open("./file1",O_RDWR);
	
	if(fd == -1){
		printf("open file1 failed\n");
		fd = open("./file1",O_RDWR|O_CREAT,0600);
		if(fd > 0){
			printf("create file1\n");
		}
	}
	printf("fd = %d\n",fd);
	
	int n_write = write(fd,buf,strlen(buf));
//	write(fd,buf,sizeof(buf));
	
	if(n_write != -1){
		printf("write %d byte to file1\n",n_write);
	}	

	close(fd);
	fd = open("./file1",O_RDWR);//写完后关闭文件,重新打开

	char *readBuf;
	readBuf = (char *)malloc(sizeof(char )*n_write + 1);	

	int n_read = read(fd,readBuf,n_write);
	
	printf("read %d,context:%s\n",n_read,readBuf);
	
	close(fd);

	return 0;
}

结果:

fd = 3
write 19 byte to file1
read 19,context:chenglong henshuai?

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值