-1

Below is a part of my code which is having issues with file handling. The file opens fine with fopen but when I try to read or just close the file my program exits without an error. I tried to run this code independently and it works fine. Would really appreciate if someone could help me out which pointing out what I am doing wrong.

    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: Updated above code

UPDATE2: Alternate code below which has same issue.

    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: Seems like the file is not opening, looking into it.

ankushkool
  • 31
  • 1
  • 4

2 Answers2

2

When you do while (!feof ...) you check each time if you have reach the end of the file. However, at no point your advance in the file (fread ?). That means this will never terminate.

TDk
  • 1,019
  • 6
  • 18
  • 1
    And `while (!feof ...)` [is always wrong anyway](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) because it returns true only *after* an attempt to read *past* the end of the file occurs. – Andrew Henle Sep 20 '17 at 15:45
  • 1
    Although this answer makes statements about the pre-edit question that appear to be true, it does not *answer* the question, which asks why the program exits silently and unexpectedly (exactly what this answer asserts it will not do). As the question original stood, this would have been better as a comment; now it is just wrong, and should be deleted. – John Bollinger Sep 20 '17 at 15:50
0

Check whether the file exists or not. You should always check whether File pointer is NULL or not after opening the file. I think your program is unable to open the file and you are trying to use the file pointer without checking which is causing undefined behavior.

kadina
  • 5,042
  • 4
  • 42
  • 83