Function stuck in an infinite loop

First post here. I built a function that should get a string and an integer from two separate files, and save them to two variables. My code is:

void getCompanyData(char * companyData, int * checkNum){

char buffer[100];
FILE * tempFile1;
FILE * tempFile2;

tempFile1 = fopen("./companyData.txt", "r");
if (tempFile1 == NULL) {
    printf("The file failed to open!\n");
    exit(1);
}
while ((fgets(buffer, sizeof(buffer), tempFile1) != NULL)){
    strcat(companyData, buffer);
}
fclose(tempFile1);

tempFile2 = fopen("./checkNum.txt", "r");
if (tempFile2 == NULL){
    printf("The file failed to open!\n");
    exit(1);
}
while (tempFile2 != NULL){
    fscanf(tempFile2, "%d", checkNum);
}
fclose(tempFile2);

}

From the companyData.txt file:

Sabre Corporation
15790 West Henness Lane
New Corio, New Mexico 65790

From checkNum.txt: 100

+4
source share
1 answer

Your function is stuck in an infinite loop because your last loop whilewill never end. The following is a loop:

while (tempFile2 != NULL){
    fscanf(tempFile2, "%d", checkNum);
}

Change it to

fscanf(tempFile2, "%d", checkNum);

and your code will work. You do not need to check tempFile != NULL, because you are already checking it in ifbefore the cycle. It is also recommended to check if it was fscanfsuccessful. Therefore use

if(fscanf(tempFile2, "%d", checkNum)==1)
    //successfully scanned an integer from tempFile2
else
    //failed to scan an integer from tempFile2
+4
source

All Articles