C语言之文件读取结束的判定和文件缓冲区

一、文件读取结束的判定

1.1 介绍

在C语言中,读取文件时,判断文件是否已经读取结束通常依赖于几个不同的函数和方法,这取决于你是如何读取文件的。

值得注意的是,在文件读取过程中,不能用feof函数的返回值直接判断文件的读取是否结束。它用于当文件读取结束的时候,判断是读取失败结束(返回值为0),还是遇到文件尾结束(返回值非零)。

int feof( FILE *stream );

判断文件是否已经读取结束通常依赖以下函数:

fgetc:fgetc return the character read as an int or return EOF to indicate an error or end of file.

读取失败返回EOF,正常读取返回的是读取到的字符的ASCII码值。

fgets:Each of these functions returns string. NULL is returned to indicate an error or an end-of-file condition. Use feof or ferror to determine whether an error occurred.

读取失败返回NULL,正常读取返回存放字符串的空间起始地址。

fread:fread returns the number of full items actually read, which may be less than count if an error occurs or if the end of the file is encountered before reaching count. Use the feof or ferror function to distinguish a read error from an end-of-file condition. If size or count is 0, fread returns 0 and the buffer contents are unchanged.

size_t fread( void *buffer, size_t size, size_t count, FILE *stream );

读取的时候返回的是实际读取到的完整元素的个数,如果发现读取到的完整的元素个数小于指定的元素个数,这就是最后一次读取了。

1.2 代码示例

如下图,在test.txt文件中预先存入了代码,现在写代码把test.txt文件拷贝一份生成text2.txt文件。

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>

int main()
{
	FILE* pfread = fopen("test.txt", "r");
	if (pfread == NULL)
	{
		perror("fopen");
		return 1;
	}
	FILE* pfwrite = fopen("test2.txt", "w");
	if (pfwrite == NULL)
	{
		fclose(pfread);
		pfread = NULL;
		return 1;
	}
	//文件打开成功
	//读写文件
	int ch = 0;
	while ((ch = fgetc(pfread)) != EOF)
	{
		//写文件
		fputc(ch, pfwrite);
	}
	if (feof(pfread))
	{
		printf("遇到文件结束标志,文件正常结束\n");
	}
	else
	{
		printf("文件读取失败\n");
	}
	//关闭文件
	fclose(pfread);
	pfread = NULL;
	fclose(pfwrite);
	pfwrite = NULL;
	return 0;
}

 

二、文件缓冲区 

文件缓存区是内存中的一块区域,用于临时存储从文件读取的数据或待写入文件的数据。使用缓存区可以减少对磁盘的直接读写次数,因为磁盘的I/O操作相对较慢。通过先在缓存区中读写数据,然后再一次性地将缓存区的数据写入磁盘或从磁盘读取数据到缓存区,可以显著提高程序的运行效率。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值