在空时阻止文件读取c中的垃圾数据 [英] prevent file read rubbish data in c when empty
本文介绍了在空时阻止文件读取c中的垃圾数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有问题,当文件为空时它会在屏幕上打印垃圾数据如何避免这种情况
这里是我的代码
i have problem when file is empty it print rubbish data on the screen how to avoid that
here is my code
void openFile()
{
int i;
char str[999];
FILE * file;
file = fopen("1.txt" , "r");
if (file)
{
while (!feof(file))
{
fscanf(file,"%d ",&i);
printf("%d ", i);
fscanf(file,"%s ",str);
printf("%s ",str);
fscanf(file,"%s",str);
printf("%s ",str);
}
fclose(file);
}
}
推荐答案
使用这样的feof非常糟糕 - 因为没有从中读取数据文件在那时,feof将返回false - 因此你打印的值是cr @ p - fscanf,fgets实际上设置了文件结束条件
你更好关闭使用while / break并在每个fscanf之后检查文件结尾 - 例如: -
using feof like that is really bad - since no data has been read from the file at that point, feof will return false - hence the values you are printing are cr@p - fscanf, fgets actually set the end of file condition
you are better off using a while/break and checking for end-of-file after every fscanf - something like :-
while( 1 ) {
/* read integer */
fscanf(file,"%d ",&i);
if ( feof(file) ) /* check for EOF right after fscanf() */
break;
printf("%d ", i);
/* read string */
fscanf(file,"%d ",&i);
if ( feof(file) ) /* check for EOF right after fscanf() */
break;
printf("%s ",str);
/* read string */
fscanf(file,"%d ",&i);
if ( feof(file) ) /* check for EOF right after fscanf() */
break;
printf("%s ",str);
}
fclose(file);
你试图在条件存在之前测试它,这将是永远不会工作您也没有检查fscanf
的错误退货,因此您的程序将打印任何旧垃圾。你最好只需一次调用fscanf
来阅读所有字段,例如:
You are trying to test for a condition before it exists, which will never work. You are also not checking for bad returns fromfscanf
, so your program will print any old rubbish. You would be better off reading all fields in a single call tofscanf
, something like:
void openFile()
{
int i;
char str1[999];
char str2[999];
FILE * file;
file = fopen("1.txt" , "r");
if (file)
{
while (fscanf(file,"%d %s %s", &i, str1, str2) == 3)
{
printf("%d ", i);
printf("%s ", str1);
printf("%s\n",str2);
}
fclose(file);
}
}
这篇关于在空时阻止文件读取c中的垃圾数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文