Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 陷入无限循环的函数_C_File Io_Infinite Loop_Fgets - Fatal编程技术网

C 陷入无限循环的函数

C 陷入无限循环的函数,c,file-io,infinite-loop,fgets,C,File Io,Infinite Loop,Fgets,第一个帖子在这里。我构建了一个函数,它应该从两个单独的文件中获取一个字符串和一个整数,并将它们存储到两个变量中。我的代码是: void getCompanyData(char * companyData, int * checkNum){ char buffer[100]; FILE * tempFile1; FILE * tempFile2; tempFile1 = fopen("./companyData.txt", "r"); if (tempFile1 == NULL) {

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

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

您的函数被卡在无限循环中,因为您的最后一个
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

函数调用也是:getCompanyData(companyData,&checkNum);“你有什么问题?”对不起,编辑了这篇文章。函数get在从companyData.txt检索数据时进入一个无限循环,我试图将缓冲区连接到companyData数组中。我的问题是,这个函数有什么问题?请阅读下面的答案