首页 > 解决方案 > 如何在文件中找到特定的单词?

问题描述

我想检查文件中是否包含“Title1, title2, title 3, title4”字样。如果文件中有这些单词,我想打印“we found the %s word in file”。

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



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

char word[4][20]={"tittle1","tittle2","tittle3","tittle4"};
char *string;
int k;
FILE *in_file = fopen("abce.txt", "r");


if (in_file == NULL)
{
    printf("Error file missing\n");

}

else{


printf("enter a array number that you want find in file");
scanf("%d",&k);

    while(!feof(in_file))
    {
        fscanf(in_file,"%s",string);
        if(!strcmp(string,word[k-1])){
            printf("we found the word %s in the file \n",string );

}
}

}
return 0;
 } 

但我无法正确编写代码。你能帮我修一下吗?谢谢你的帮助...

标签: c

解决方案


我不得不做一些重构。

stringchar *但从未分配过。因此,fscanf将出现段错误。

word可能是char *word[]

strcmp需要连接到printf

您需要rewind先扫描文件,然后再扫描每个新词。

其他修复...

无论如何,这是代码:

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

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

    char *word[] = { "tittle1", "tittle2", "tittle3", "tittle4" };
    char string[1000];
    int k;
    FILE *in_file = fopen("abce.txt", "r");

    if (in_file == NULL) {
        printf("Error file missing\n");
        exit(1);
    }

    while (1) {
        printf("enter a array number that you want find in file: ");
        fflush(stdout);
        scanf("%d", &k);

        if (k < 0)
            break;

        if (k >= (sizeof(word) / sizeof(word[0]))) {
            printf("invalid index -- %d\n",k);
            continue;
        }

        rewind(in_file);
        int wordidx = 0;
        while (1) {
            if (fscanf(in_file, " %s", string) != 1)
                break;
            //printf("DEBUG: '%s'\n",string);

            if (strcmp(string, word[k]) == 0) {
                printf("we found the word '%s' in the file at offset %d\n",
                    word[k],wordidx);
                break;
            }

            ++wordidx;
        }
    }

    return 0;
}

推荐阅读