我有一个带有单个名称的文本文件(names.txt),例如:
mary
john
kj
mark
我试图将它们与另一个文本文件(records.txt)中的其他数据相匹配,它看起来像这样:
mary jon mik 200 west 90
fgg gh 400 east 700
james ggg 890 south 800
john nike 556 4666
正在阅读 names.txt 并针对 records.txt 运行名称,如果名称与 records.txt 中的整行匹配则打印。当我从 CL 中一一输入名称时,没关系。但是当我从文本文件中调整代码以按照上述方式执行时,它不起作用。有人可以指出正确的方向。这是我的代码:
/*program to search for a given string from a file*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int usage(char*argv[]);
int main (int argc,char*argv[])
{
int flag=0,i=0;
FILE*fp,*lp;
char line[50];
char word[10];
lp=fopen(argv[1],"r");
fp=fopen(argv[2],"r");
if (argc!=3) {
usage(argv[0]);
exit(0);
}
if (lp==NULL || fp==NULL) {
perror("can't open file");
exit(1);
}
//getting words to search
while (fgets(word,10,lp)!=NULL) {
for(i=0;i<=strlen(word);i++){
if(word[i]=='\n'){
word[i]='\0';
break;
}
}
printf("searching for %s in %s ",word,argv[2]);
//searching in file
i=0;
while (fgets(line,50,fp)!=NULL) {
i++;
if(strstr(line,word)!=NULL){
printf("%s found in line %d\n%s.\n",word,i,line);
flag=1;
}
}
if(flag==0)
puts("no match found");
flag=0;
}
putchar('\n');
exit(0);
}
int usage(char*argv[])
{
printf("usage:\n<argv> <source file> < search file>\n");
return 0;
}
运行上面的代码,得到的是:
searching for mary
in records.txt
jon mik mary 56 567
mary found in line 1
jon mik mary 56 56
searching for john
in records.txt
no match found
searching for kj
in records.txt
no match found
searching for mark in records.txt
no match found