我有这个功能来读取结构如下的txt文件中的数字:
1 2 5
2 1 9
3 5 8
该函数将值正确读入我的值,但我想检查我读过的行是否是文件中的最后一行。
我在下面的函数中的最后一个if语句尝试通过查看fscanf是否产生NULL但它不起作用来执行此操作,即使该函数不是最后一行,该函数也始终返回NULL。
void process(int lineNum, char *fullName)
{
int ii, num1, num2, num3;
FILE* f;
f = fopen(fullName, "r");
if(f==NULL)
{
printf("Error: could not open %S", fullName);
}
else
{
for (ii=0 (ii = 0; ii < (lineNum-1); ii++)
{
/*move through lines without scanning*/
fscanf(f, "%d %d %d", &num1, &num2, &num3);
}
if (fscanf(f, "%*d %*d %*d\n")==NULL)
{
printf("No more lines");
}
fclose(f);
}
}
答案 0 :(得分:1)
检查以下代码。使用此代码,您可以查看是否已到达文件末尾。建议不要使用fscanf来读取文件末尾。
/ * feof示例:字节计数器* /
#include <stdio.h>
int main ()
{
FILE * pFile;
int n = 0;
pFile = fopen ("myfile.txt","r");
if (pFile==NULL) perror ("Error opening file");
else
{
while (fgetc(pFile) != EOF) {
++n;
}
if (feof(pFile)) {
puts ("End-of-File reached.");
printf ("Total number of bytes read: %d\n", n);
}
else puts ("End-of-File was not reached.");
fclose (pFile);
}
return 0;
}
答案 1 :(得分:0)
您可以使用feof()
检查您是否正在阅读文件末尾。
来自fscanf
的手册页:
返回值 这些函数返回成功匹配的输入项的数量 和分配,可以少于提供,甚至零 早期匹配失败的事件。
如果您尝试阅读的最后一行不符合预期格式,fscanf
可能无法阅读任何内容并返回与0
相同的NULL
。