pre{
line-height:1;
color:#38ede1;
background-color:#5b2814;
font-size:16px;}.sysFunc{color:#008080;font-style:italic;font-weight:bold;}
.selfFuc{color:#008080;}
.bool{color:#952fa4;}
.condition{color:#ca5cb9;font-weight:bold;}
.key{color:#85d7e6;}
.var{color:#a6caf0;font-style:italic;}
.Digit{color:#c0c0c0;font-weight:bold;}
.includePre{color:#e1ed38;}
.operator {color:#6de9b8;font-weight:bold;}
test.txt 中保存的为:
1
2
3
4
5
程序
int i,j,k;
FILE *fp=fopen("e://test.txt","r");
if (fp==NULL)
{
//return FALSE;
}
while (!feof(fp))
{
j=fscanf(fp,"%d%d",&i,&k);
cout<<i<<'/t'<<k<<'/t'<<j<<endl;
}
输出结果为:
1 2 2
3 4 2
5 4 1
OK
若是将test.txt中的内容改为: 1 2 3 4
则输出结果为:
1 2 2
3 4 2
3 4 -1
OK
fscanf() 在进行第一次转换之前就已经到了末尾或者有读错误时 则其返回值为EOF(-1), 否则得话,则返回其成功转换的元素数目。
可以根据这个性质,来控制文件读写。
MSDN中对返回值的解释为:
Each of these functions returns the number of fields successfully converted and assigned; the return value does not include fields that were read but not assigned. A return value of 0 indicates that no fields were assigned. If an error occurs, or if the end of the file stream is reached before the first conversion, the return value is EOF for fscanf and fwscanf.
--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
feof() 标志 在读完最后一个元素后,仍是正常的,只有再试图读新的元素时,才知道到了末尾,这时才修改状态
读文件时,要清楚这个判断结尾的原理,否则很容易多读一写内容
例子:
下面的程序
[c-sharp] view plaincopy
while (!feof(fp)) {
if (fscanf(fp, "%lf", &x) == 1)// 返回值为1时正确
{
。。。。。//正确读入时的处理情况
}
}
fclose(fp);
本文使用 书画小说软件 发布,内容与软件无关,书画小说软件 更惬意的读、更舒心的写、更轻松的发布。