fscanf和feof的组合使用
http://stackoverflow.com/questions/15719360/using-fscanf-using-feof
靶子代码:
#include<stdio.h> void main(){FILE *fp;int a,b;fp=fopen("hello.txt","r");while(!feof(fp)){fscanf(fp,"%d %d",&a,&b);printf("%d %d\n",a,b);} }
My hello.txt is
1 2
3 4
My Output is
1 2
3 4
4 4
解决方法
1. It means that the way the feof()
function (and other functionality with regards to EOF in general) is used is often misunderstood and wrong. So is your code.
First, fscanf()
doesn't always do what you think it does, and getting lines from a file is better performed using fgets()
. However, if you're really inclined to use fscanf()
, then check if it could read someting at all, else when it couldn't, you will print the variables one time more than needed. So what you should do is:
while (fscanf(fp,"%d %d",&a,&b) == 2) {printf("%d %d\n",a,b); }
2.The reason you're getting an extra line is that EOF isn't set until after fscanf
tries to read a third time, so it fails, and you print the results anyway. This would do the sort of thing you've intended
while(1){fscanf(fp,"%d %d",&a,&b);if (feof(fp))break;printf("%d %d\n",a,b); }
转载于:https://www.cnblogs.com/lixiaohui-ambition/p/3747715.html
fscanf和feof的组合使用相关推荐
- 20160301.CCPP体系详解(0040天)
程序片段:01.fscanfprintf.c+02.51Job.c+03.7K7K.c 内容概要:fscanffprintf ///01.fscanfprintf.c #define _CRT_SEC ...
- feof函数,fscanf函数,strtok函数等遇到的小疑惑解决办法
feof函数,fscanf函数,strtok函数等遇到的小疑惑解决办法 近几天我等几个小菜鸟要做一个快译通软件,简单实现根据英语查汉语,本人负责将dict.txt词库中的单词调入内存哈希表 ...
- c语言从.txt读入第二行数,从txt中读入数据到数组中(fscanf)的实现代码
从txt中读入数据到数组中(fscanf)的实现代码 C-sources: #include int main() { FILE* fp; //定义一个文件 fp = fopen("p5.t ...
- matlab中的fscanf函数,matlab中fscanf函数
Matlab之print,fprint,fscanf,disp函数_数学_自然科学_专业资料.print: print 函数可以把函数图形保存成图片: minbnd = -4*pi; maxbnd = ...
- 使用fscanf读取文本文件
fscanf为读取文本文件的一个c API,其特点是可格式化读取文件内容. 1 FILE* pf = fopen("c:\\hello.txt", "r"); ...
- 【C 语言】文件操作 ( 读取文件中的结构体数组 | feof 函数使用注意事项 )
文章目录 一.读取文件中的结构体数组 | feof 函数使用注意事项 二.代码示例 一.读取文件中的结构体数组 | feof 函数使用注意事项 读取文件结构体时 , 可以循环读取文件中的数据 , 只使 ...
- 【C++ 语言】文件操作 ( fopen | fprintf | fscanf | fgets | fputc | fgetc | ofstream | ifstream )
文章目录 I C 函数 fopen 打开文件 II C 函数 fprintf 写出文件 III C 函数 fscanf 读取文件 ( 遇到空格换行结束) IV C 函数 fgets 读取文件 ( 遇到 ...
- c语言如何用fscanf将字符串读取,在c语言中如何将文本内容 赋给一个 字符串
在c语言中如何将文本内容 赋给一个 字符串 来源:互联网 宽屏版 评论 2009-08-13 04:59:12 分类: 电脑/网络 >> 程序设计 >> 其他编程语言 问题 ...
- fscanf简单使用
简单使用下fscanf #include <stdio.h> #include <stdlib.h> int main() {int num, number;char name ...
最新文章
- ArcEngine中的缩放地图
- 通过Runtime源码了解关联对象的实现
- solr定时实时重建索引和增量更新
- 动态规划进阶题目之滑雪
- 18.linux日志收集数据到hdfs上面
- java基础知识总结(经典)_Java基础知识总结(超级经典)(三)
- pygame学习笔记(6)——一个超级简单的游戏
- ARToolkit Part 1: Labelling 详解
- 开发游戏引擎需要具备什么
- csgo如何旋转跳?如何连跳
- Swift:一个简单的货币转换器App在iOS10中的分析和完善
- [PTA] 7-11 计算平均分
- iOS二十种超酷时尚艺术滤镜汇总
- 解决phpmyadmin 访问卡慢等问题
- Unknown database ‘xxx‘
- 武汉理工实验3 循环结构(1)——7-3 最大公约数和最小公倍数
- PQ和HLG标准及其转换
- Could not find messages which '/home/flying/catkin_ws/src/beginner_tutorials/msg/Num.msg' depends
- unity3D射击游戏
- adwcleaner_AdwCleaner中文版