【问题标题】:fscanf() fclose() or reading file exit and ends programfscanf() fclose() 或读取文件退出并结束程序
【发布时间】:2017-09-20 15:40:09
【问题描述】:

以下是我的代码的一部分,它在文件处理方面存在问题。该文件可以使用 fopen 正常打开,但是当我尝试读取或关闭该文件时,我的程序会退出而不会出现错误。我试图独立运行这段代码,它工作正常。如果有人能帮助我指出我做错了什么,我将不胜感激。

    int ctrlSend(char *etherPort, uint8_t *inPayload, int payloadLen, int vlanID) 
    {
    char intName [10]; // Interface name from file
    int intVlan; // Interface VLAN from file
    printf("In ctrlSend\n");

    FILE * pFile; // File pointer
    pFile = fopen ("vlan.conf","r");

    while(!feof(pFile))
    {
      fscanf(pFile,"%s %d",intName,&intVlan)
      printf("In ctrlSend while loop");
    }


    fclose (pFile);
    return 0;
    }

UPDATE1:更新了上面的代码

UPDATE2:下面有相同问题的备用代码。

    int ctrlSend(char *etherPort, uint8_t *inPayload, int payloadLen, int vlanID) 
    {

    printf("In ctrlSend\n");

    char intName [10]; // Interface name from file
    int intVlan; // Interface VLAN from file
    FILE * pFile; // File pointer
    pFile = fopen ("vlan.conf","r");

    while (fscanf (pFile,"%s %d",intName,&intVlan) == 2)
    {
        printf("In ctrlSend while loop");
    }


    fclose (pFile);
    return 0;
    }

UPDATE3:好像文件没有打开,正在查看。

【问题讨论】:

  • while 循环不会因非空文件而终止。看起来与您所描述的问题相反。
  • @EugeneSh。它不会为 any 文件终止,即使是空的。
  • 使用前没有测试fopen()的返回值,你怎么知道文件“打开正常”?
  • 你怎么知道对fscanf() 的add-by-a-recent-edit 调用有效?您没有检查 任何内容 是否有错误。

标签: c file scanf fopen file-handling


【解决方案1】:

当您执行while (!feof ...) 时,您每次都会检查您是否已到达文件末尾。但是,您在文件中的任何进展都没有(fread ?)。这意味着这将永远不会终止。

【讨论】:

  • while (!feof ...) is always wrong anyway 因为它仅在尝试读取过去文件末尾时返回true。
  • 虽然这个答案使关于预编辑问题的陈述看起来是真的,但它并没有回答这个问题,它询问程序为什么静默和意外退出(确切地说这个答案断言它不会做什么)。正如最初的问题所代表的那样,作为评论会更好;现在它是错误的,应该删除。
【解决方案2】:

检查文件是否存在。打开文件后,您应该始终检查文件指针是否为 NULL。我认为您的程序无法打开文件,并且您尝试使用文件指针而不检查导致未定义行为的原因。

【讨论】:

  • 这是一个很好的建议,文件没有正确打开。谢谢
猜你喜欢
  • 1970-01-01
  • 2011-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多