比较C中两个while循环中两个文件的字符串

时间:2014-04-22 00:43:24

标签: c while-loop

我试图找到两个txt文件中的字符串(一个来自argv [2],一个来自stdin),但是我的循环只测试第一个文件中的第一行字符串,剩下的第二个文件。我似乎无法弄清楚为什么我的程序不会回到"位置来检查"尽管有while循环,但每张票都有。

#include <stdio.h>
#include <string.h>

#define BUFLEN (15)

int main(int argc, char *argv[]) {

char buf[15];
char buflocation[6];
char location[6];

FILE *fp = fopen(argv[2],"r");


while (fgets(buf, BUFLEN, stdin) != NULL) {
    int i;

    for (i = 0; i<4; i++){
        location[i] = buf[i];

    }

    printf("location of ticket we are testing is %s\n",location);

    while (fgets(buflocation,sizeof(buflocation),fp) != NULL){


            printf("location to check against:%s",buflocation);
                if (strncmp(location,buflocation,4) == 0){
                        printf("this ticket is valid %s\n",buf);
                    }
    }
}



fclose(fp);
return 0;

}

这是输出

location of ticket we are testing is 1111
location to check against:0101
location to check against:0027
location to check against:1009
location to check against:0077
location to check against:1111
this ticket is valid 111122222220
location of ticket we are testing is 1111
location of ticket we are testing is 9876
location of ticket we are testing is 4526
location of ticket we are testing is 7368

所以,如果我的下一张票是100967789654,那么它也应该是有效的,因为1009是一个有效的位置,但它只是没有读入第二行。我没有正确宣布我的时间陈述吗?

2 个答案:

答案 0 :(得分:1)

内部while循环保持将文件读取到最后。在外循环的第二次迭代中,文件已经位于文件末尾。要强制重新读取,您需要使用以下命令将文件重新定位到开头:

fseek(fp, 0, SEEK_SET);

答案 1 :(得分:1)

填充char数组时,需要使用'\0'字符

终止它

示例:

#include <stdio.h>
#include <string.h>

main()
{
   char location[10];

   location[0]='a';
   location[1]='b';
   location[2]='c';
   location[3]='\0'; // not adding this is undefined behavior

   printf("%s", location);
}