fscanf() fclose() 或读取文件退出并结束程序

fscanf() fclose() or reading file exit and ends program

下面是我的代码中存在文件处理问题的部分。该文件可以用 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:更新了上面的代码

更新 2:下面的替代代码也有同样的问题。

    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 (!feof ...) 时,您每次都会检查是否已到达文件末尾。但是,您绝不会在文件中前进(fread?)。这意味着这将永远不会终止。

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