【问题标题】:Function stuck in an infinite loop函数陷入无限循环
【发布时间】:2014-12-14 03:41:02
【问题描述】:

第一次发帖。我已经构建了一个函数,它应该从两个单独的文件中获取一个字符串和一个整数,并将它们存储到两个变量中。我的代码是:

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

【问题讨论】:

  • 函数调用也是:getCompanyData(companyData, &checkNum);
  • 你有什么问题?
  • @CoolGuy 抱歉,编辑了帖子。该函数在从 companyData.txt 检索数据时进入无限循环,我试图将缓冲区连接到 companyData 数组中。我的问题是,这个函数有什么问题?
  • 在下面阅读我的答案

标签: c file-io infinite-loop fgets


【解决方案1】:

您的函数陷入无限循环,因为您的最后一个 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

【讨论】:

    猜你喜欢
    • 2017-12-05
    • 2021-12-17
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 2013-03-17
    相关资源
    最近更新 更多