C strstr 无法正常工作
C strstr not working correctly
我正在尝试使用 strstr 来搜索任何使用子字符串的匹配项,并将其与一行文本进行比较,但到目前为止尚未成功获得匹配项。我正在使用 popen 打开和读取文件,同时尝试仅使用 ipv4 地址进行搜索以查找匹配项。我的代码有什么问题?非常感谢任何帮助,谢谢。
char *buffe = malloc(sizeof(char));
FILE *rib_file = popen("bgpdump -Mv rib.20160101.0000.bz2", "r");
while(fgets(buffe, sizeof(buffe), rib_file)!=NULL) {
if(buffe[strlen(buffe)-1] == '\n')
buffe[strlen(buffe)-1] = '[=10=]';
for (int i = 0; i < argc; i++) {
if((strstr(buffe, argv[i])) != NULL) {
printf("A match found on line: %d\n", line_num);
printf("\n%s\n", buffe);
find_result++;
}
line_num++;
}
}
if(find_result == 0) {
printf("\nSorry, couldn't find a match.\n");
}
if (rib_file) {
pclose(rib_file);
}
free(buffe);
}
buffe 的例子:
TABLE_DUMP2|01/01/16 00:00:38|B|202.232.0.3|2497|223.255.254.0/24|2497 7473 3758 55415|IGP
当我的代码找到匹配项时,我正在尝试打印上面的确切行。
sizeof
函数告诉您类型的大小。由于 buffe
是一个指针,您对 sizeof(buffe)
的调用将使您获得平台上指针的大小,这几乎肯定不是您想要的。您是要传递 fgets
buffe
指向的东西的大小吗?
我正在尝试使用 strstr 来搜索任何使用子字符串的匹配项,并将其与一行文本进行比较,但到目前为止尚未成功获得匹配项。我正在使用 popen 打开和读取文件,同时尝试仅使用 ipv4 地址进行搜索以查找匹配项。我的代码有什么问题?非常感谢任何帮助,谢谢。
char *buffe = malloc(sizeof(char));
FILE *rib_file = popen("bgpdump -Mv rib.20160101.0000.bz2", "r");
while(fgets(buffe, sizeof(buffe), rib_file)!=NULL) {
if(buffe[strlen(buffe)-1] == '\n')
buffe[strlen(buffe)-1] = '[=10=]';
for (int i = 0; i < argc; i++) {
if((strstr(buffe, argv[i])) != NULL) {
printf("A match found on line: %d\n", line_num);
printf("\n%s\n", buffe);
find_result++;
}
line_num++;
}
}
if(find_result == 0) {
printf("\nSorry, couldn't find a match.\n");
}
if (rib_file) {
pclose(rib_file);
}
free(buffe);
}
buffe 的例子:
TABLE_DUMP2|01/01/16 00:00:38|B|202.232.0.3|2497|223.255.254.0/24|2497 7473 3758 55415|IGP
当我的代码找到匹配项时,我正在尝试打印上面的确切行。
sizeof
函数告诉您类型的大小。由于 buffe
是一个指针,您对 sizeof(buffe)
的调用将使您获得平台上指针的大小,这几乎肯定不是您想要的。您是要传递 fgets
buffe
指向的东西的大小吗?