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

标签 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 是一个有效位置,但它不会读入第二行。我没有正确声明我的 while 语句吗?

最佳答案

内部的 while 循环一直读取文件到最后。在外循环的第二次迭代中,文件已经位于文件末尾。要强制重读,​​您需要将文件重新定位到开头:

fseek(fp, 0, SEEK_SET);

关于在C中的两个while循环中比较来自两个文件的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23208436/

相关文章:

c++ - 椭圆滤波器代码

C 函数有时返回太慢

c - 当我们用正常的内存分配替换/dev/mem 映射时,8 位内存访问的行为如何

c++ - WHILE 循环和数据输入

java - 循环内的随机数生成器

c - 传递数组时在C中的函数参数中强制数组大小

c - C中如何读入变量名及其对应的值

Java 代码在使用用户输入循环运行时保持读入文件

c - 在 C 中时(使用 log Not)

javascript - 在给定的时间间隔内尽可能多次地调用函数