检测的feof文件的假结束 [英] feof detecting false end of file

查看:139
本文介绍了检测的feof文件的假结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我问这个早了不同的问题,但我是大错特错了那么我创建了一个新的问题,因为我要问一个完全不同的问题。这个问题

I asked a different question about this earlier, but I was way off base about the problem so I've created a new question as I'm asking an entirely different question.

我有一个函数读取一个文本文件中的给定线(由交流变频给出)。它执行的行的读出,然后检查,如果这是在该文件中的最后一行。如果因此增加的值。

I have a function that reads a given line in a text file (given by ac variable). It performs the read of the line and then checks if that was the last line in the file. If so it increments a value.

的问题是,它的增加的值,即使它不是文件的实际结束。我想我使用的feof错了,但我已经没有运气得到它的工作:

The problem is that it's incremented the value even when it's not the actual end of the file. I think I'm using feof wrong but I've had no luck getting it to work:

int readIn(TinCan* inCan, int toggle)
  {
  int ii, isFinished = 0;
  char fullName[20];
  sprintf(fullName, "Label_%d.txt", inCan->pid);

  FILE* fp; 
    fp = fopen(fullName, "r");

    if(fp==NULL) 
      {
      printf("Error: could not open %s\n", fullName);
      }

    else
      {
      for (ii=0; ii < ((inCan->ac)-1); ii++)
        {
        fscanf(fp, "%*d %*d %*d\n"); /*move through lines without scanning*/
        }
      fscanf(fp,"%d %d %d", &inCan->ac, &inCan->state, &inCan->time);
      }

    if (feof(fp) && (toggle == 1)) 
      {
      printf("File ended"); 
      writeLog(inCan);
      isFinished = 1;
      terminated++;
      }

  fclose(fp);
  return finished;
  }

根据要求

样本数据,这是一个文本文件,我可以用:

Sample data as requested, this is a text file I may use:

1 1 30
2 2 5
3 1 1

FSCANF正确分配值。在第二行,的feof返回true,终止递增。的feof再次为第3行返回true,增量结束了第二次。

fscanf correctly assigns the values. On the second line, feof returns true and terminated is incremented. feof returns true again for the 3rd line and increments terminated a second time.

推荐答案

的feof()不如果文件已经结束检测。它可以检测,如果最后读取错误是由于已经结束的文件。

feof() does not detect if the file has ended. It detects if the last read error was due to the file having ended.

的feof()只是读取失败后会发生。

feof() only happens after a failed read.

所以,首先读取数据和检查返回值。如果读取失败使用的feof(),以确保它失败,因为档案结尾达到(其他原因读取失败是某种(网络错误下来,坏扇区,起火打印机,...),检测与 FERROR())。

So, first read data and check the return value. If the read failed use feof() to make sure it failed because the END-OF-FILE was reached (other reasons for the read to fail are error of some kind (network down, bad sector, printer on fire, ...), detectable with ferror()).

这篇关于检测的feof文件的假结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆