C初学者:如何在C中搜索文件中的特定单词(逐行)

时间:2012-04-20 03:17:21

标签: c file while-loop strcmp

我需要逐行搜索文件中的两个特定单词,如果存在,请打印“找到!”。

这是file.txt(有四列)

bill gates 62bill microsoft 
beyonce knowles 300mill entertainment 
my name -$9000 student

以下是我的想法,但它似乎不起作用

char firstname[];
char lastname[];
char string_0[256];

file = fopen("file.txt","r+");

while((fgets(string_0,256,file)) != NULL) {

  //scans the line then sets 1st and 2nd word to those variables
  fscanf(file,"%s %s",&firstname, &lastname);

  if(strcmp(firstname,"beyonce")==0 && strcmp(lastname,"knowles")==0){
    printf("A match has been found");
  }
}

fclose(file);

请帮忙。可能是指针没有移动到while循环中的下一行吗?如果是这样,我该如何解决?

2 个答案:

答案 0 :(得分:4)

在您使用fscanf读取file后,fgets上的sscanf不是在string_0上调用,而应该在fgets变量上调用{{1}}您要将数据复制到{{1}}来电。

答案 1 :(得分:4)

一种方法是使用fget函数并在文本中查找子字符串。尝试这样的事情:

int main(int argc, char **argv)
{
    FILE *fp=fopen(argv[1],"r");
    char tmp[256]={0x0};
    while(fp && fget(tmp, sizeof(tmp), fp))
    {
        if (strstr(tmp, "word1"))
            printf("%s", tmp);
        else if (strstr(tmp, "word2"))
            printf("%s", tmp);
    }
    if(fp) fclose(fp);
    return 0;
}
相关问题