首先发布在这里。我已经构建了一个函数,它应该从两个单独的文件中获取一个字符串和一个整数,并将它们存储到两个变量中。我的代码是:
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);
}
来自companyData.txt:
Sabre Corporation
15790 West Henness Lane
New Corio, New Mexico 65790
来自checkNum.txt: 100
答案 0 :(得分:4)
您的函数陷入无限循环,因为您的上一个while
循环永远不会结束。以下循环是造成问题的一个:
while (tempFile2 != NULL){
fscanf(tempFile2, "%d", checkNum);
}
将其更改为
fscanf(tempFile2, "%d", checkNum);
您的代码将有效。您不需要检查tempFile != NULL
,因为您已经在循环之前在if
中检查了它。此外,检查fscanf
是否成功是一个好习惯。所以使用
if(fscanf(tempFile2, "%d", checkNum)==1)
//successfully scanned an integer from tempFile2
else
//failed to scan an integer from tempFile2