【问题标题】:fgetc() returns EOF when stream is not 0当流不为 0 时 fgetc() 返回 EOF
【发布时间】:2020-05-25 14:00:50
【问题描述】:

我正在尝试从二进制文件中读取字符并将它们与另一个二进制文件中的字符进行比较,但我想从中间开始读取其中一个文件,而不是从头开始。当我尝试它时,我无法从中间读取我试图读取的文件,因为它立即返回 EOF。我尝试从不同的角度读取它,甚至将流移动到一个位置,但它仍然立即返回 EOF。

int scanWithOffset(FILE* fc, FILE* fv, int start, int end)
{
    int charRead1 = 0, charRead2 = 0, matchCounter = 0, match = 0;
    int fileSize = findFileSize(fv);
    int counter = 0;

    if (!fseek(fc, start, SEEK_SET))
    {
        while (((charRead2 = fgetc(fv)) != EOF) && ((charRead1 = fgetc(fc)) != EOF)
               && !match && counter < (end - start))
        {
            counter++;
            if (charRead1 == charRead2)
            {
                matchCounter++;
                if (matchCounter == fileSize)
                {
                    match = 1;
                    fclose(fc);
                }
            }
            else
            {
                // if something doesn't match up, reset the counter and bring
                // the stream back to the beginning
                matchCounter = 0; 
                fseek(fv, 0, SEEK_SET);
            }
        }

        if (!match)
        {
            fclose(fc);
        }
    }

    return match;
}

【问题讨论】:

  • 如果你把fseek alltogether 一起丢掉会有用吗?
  • 放下它确实可以,但是我仍然需要从文件的某个部分读取它,我不能只是从头到尾读取它。我还修正了错字,但没有帮助。
  • 如果您用start = 0 调用scanWithOffset 会发生什么?
  • 如果我这样做,它会起作用。
  • 验证哪个文件操作触发了EOF信号。可能是fgetc(fc) 或fgetc(fv)...也许打印ferror(fv)?

标签: c fseek fgetc


【解决方案1】:
if (matchCounter == fileSize)
{
   match = 1;
   fclose(fc);
}

关闭fc 后,您不会中断while 循环。当您到达matchCounter == fileSize 时,您必须退出while 循环。你可以在fclose(fc)后面加break;:

if (matchCounter == fileSize)
{
   match = 1;
   fclose(fc);
   break;
}

【讨论】:

  • 我不确定这是否是他的问题的真正原因。
  • 这不会改变任何事情,因为在 if 语句之后它无论如何都会回到 while 循环的开头并且由于匹配为真而无法继续它
  • @EgorMatuk 为什么不呢,match 的条件是在charRead1 = fgetc(fc)) != EOF 之后的while 条件。这意味着您在验证match的条件之前重新读取文件
猜你喜欢
  • 1970-01-01
  • 2012-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-11
  • 1970-01-01
  • 2016-12-08
  • 1970-01-01
相关资源
最近更新 更多