当前位置:网站首页>文本读取结束判定
文本读取结束判定
2022-07-20 08:46:00 【腿毛ger】
1. 文本文件读取是否结束,判断返回值是否为 EOF ( fgetc ),或者 NULL ( fgets )
例如: fgetc 判断是否为 EOF .
fgets 判断返回值是否为 NULL .
2. 二进制文件的读取结束判断,判断返回值是否小于实际要读的个数。 例如: fread判断返回值是否小于实际要读的个数
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int c; // 注意:int,非char,要求处理EOF
FILE* fp = fopen("test.txt", "r");
if(!fp) {
perror("File opening failed");
return EXIT_FAILURE;
}
//fgetc 当读取失败的时候或者遇到文件结束的时候,都会返回EOF
while ((c = fgetc(fp)) != EOF) // 标准C I/O读取文件循环
{
putchar(c);
}
//判断是什么原因结束的
if (ferror(fp))
puts("I/O error when reading");
else if (feof(fp))
puts("End of file reached successfully");
fclose(fp);
}
二进制文件的例子:
#include <stdio.h>
enum { SIZE = 5 };
int main(void)
{
double a[SIZE] = {1.,2.,3.,4.,5.};
FILE *fp = fopen("test.bin", "wb"); // 必须用二进制模式
fwrite(a, sizeof *a, SIZE, fp); // 写 double 的数组
fclose(fp);
double b[SIZE];
fp = fopen("test.bin","rb");
size_t ret_code = fread(b, sizeof *b, SIZE, fp); // 读 double 的数组
if(ret_code == SIZE) {
puts("Array read successfully, contents: ");
for(int n = 0; n < SIZE; ++n) printf("%f ", b[n]);
putchar('\n');
} else { // error handling
if (feof(fp))
printf("Error reading test.bin: unexpected end of file\n");
else if (ferror(fp)) {
perror("Error reading test.bin");
}
}
fclose(fp);
}
边栏推荐
猜你喜欢
Operation methods and skills of CAD perfect transformation to ArcGIS
链式存储结构的线性表
旋转框目标检测mmrotate v0.3.1 训练HRSC2016数据集(二)
多线程理论基础
[hbuilder runs to the problem that Mumu simulator cannot install the base, and it has been stuck in the installation base...]
Use r to delete rows with empty cells from Excel
VOD constructs its own player, and the user calls the interface to obtain the video playback address
TP5.1 登录 配置是否登录公共函数的方法(完整的登录案例)
Drawing multi group Y-axis truncation graph with R language
【考研词汇训练营】Day 9 —— vital,dynasty,previous,praise,transit,virile,invent
随机推荐
PHP gets the website root directory, and several methods for PHP to get the website root directory
MGRE.HDLC.PPP.CHAP.NAT综合实验
Tp5.1 open the web address and output the web page code without transformation and rendering (template return $this- & gt; fetch() return view();)
Introduction to open source lightweight workflow workflowcore
《BBC 跟拍 49 年:穷人与富人的人生七年》
6.0 取消会员注册验证码
Cloud foundry development 4 CF command
Leetcode-152- maximum array of products
BBC follow-up 49 years: seven years of life for the poor and the rich
R语言 | jiebaR 词频统计
C#入门系列(二十五) -- 接口
PHP login and exit login logic
The best method of converting string to date in R language
链表的应用
R语言世界价值观调查作业
永久挂载镜像步骤
旋转框目标检测mmrotate v0.3.1 训练HRSC2016数据集(二)
Unity学习笔记 球形全景图平面像素坐标与三维坐标系上的坐标之间的转换
R language optimization problem
Changsha big screen development