0

我有这个函数可以从结构如下的 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);

        }
      }
4

2 回答 2

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;
}
于 2013-05-15T05:56:44.893 回答
0

您可以使用它feof()来检查您是否正在阅读文件末尾。

从手册页fscanf

返回值 这些函数返回成功匹配和分配的输入项的数量,该数量可能少于提供的数量,或者在早期匹配失败的情况下甚至为零。

如果您尝试读取的最后一行不是预期的格式,fscanf则可能不会读取任何内容并返回0NULL.

于 2013-05-15T05:47:45.920 回答