在C语言中查找文件中的字符串

4
我正在尝试编写一个程序,可以在名为student.txt的文件中搜索字符串。如果程序在文件中找到了相同的单词,我希望程序能够打印该单词,但是出现了错误。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char const *argv[])
{
int num =0;
char word[2000];
char *string[50];

FILE *in_file = fopen("student.txt", "r");
//FILE *out_file = fopen("output.txt", "w");

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

while(student[0]!= '0')
{
    printf("please enter a word(enter 0 to end)\n");
    scanf("%s", student);


    while(!feof(in_file))
    {
        fscanf(in_file,"%s", string);
        if(!strcmp(string, student))==0//if match found
        num++;
    }
    printf("we found the word %s in the file %d times\n",word,num );
    num = 0;
}

return 0;
 } 

if(!strcmp(string, student))==0 应该替换为 if(!strcmp(string, student)==0)。 - Anshul
仍然出现错误。 - jimo
你具体遇到了什么样的错误? - mushfek0001
你是在寻找字符串搜索还是单词搜索?例如,如果你正在搜索一个字符串“to”,而文件内容为:<tom took two tomatoes to make a curry>。输出结果将会是5。但实际上只有一个单词“to”。 - Anshul
3个回答

5

添加了一个最简单的示例代码。注意处理任何边缘情况。 如果您正在搜索字符串“to”。并且文件内容是:

<tom took two tomatoes to make a curry> . 

输出将会是5。但实际上只有一个单词“to”。

代码:

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

int main(int argc, char const *argv[])
{
        int num =0;
        char word[2000];
        char string[50];
        char student[100] = {0};

        while(student[0]!= '0')
        {
                FILE *in_file = fopen("student.txt", "r");
                if (in_file == NULL)
                {
                        printf("Error file missing\n");
                        exit(-1);
                }

                printf("please enter a word(enter 0 to end)\n");
                scanf("%s", student);
                while ( fscanf(in_file,"%s", string) == 1)
                {
                        //Add a for loop till strstr(string, student) does-not returns null. 
                        if(strstr(string, student)!=0) {//if match found
                                num++;
                        }
                }
                printf("we found the word %s in the file %d times\n",student,num );
                num = 0;
                fclose(in_file);
        }
        return 0;
}

正如我的同事所说,我们需要再增加一个循环来遍历同一行中任何进一步出现的同一单词。

注意: 如果您只想计算单词“to”的数量,请确保检查所有可能的单词分隔符(例如空格、逗号、句号、换行符、感叹号、和号、等于号以及其他可能性)的“string - 1”和“string + 1”字符。一个简单的方法是使用strtok,它会根据参数中指定的分隔符将缓冲区标记化为单词。请查看如何使用strtok。

http://www.tutorialspoint.com/c_standard_library/c_function_strtok.htm


谢谢,但是抱歉在这里让事情变得混乱,我正在寻找这个单词。就像你提到的例子,我希望我的程序能够找到并打印“to”。 - jimo
你肯定需要使用strtok或其他方式解析单词。按照现有的写法,你的代码每行只计算一次出现。 - Jim Mischel

0
要么在最后一个printf()行中使用变量student,要么将匹配的文本放入变量word中,并检查您的if条件。

0
你应该从文件中读取(创建一个函数)单词。这里的单词指的是由空格包围的非空白字符数组(但不要将空格记录在单词列表中)。然后通过单词列表(或实时搜索单词)查找所需的单词。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接