在文本文件C中搜索关键字

时间:2014-05-21 19:48:55

标签: c file search keyword

我无法从用户输入搜索的文件中读取关键字。程序的第一部分要求用户输入命名文件。然后它要求输入句子。您可以输入句子,直到您写完"结束"。当您编写" END"时,句子到文件的附加应该停止,程序应该要求您输入关键字来搜索附加到新创建的文本文件的句子。我用过'得到'要求在文件中搜索一个单词。程序应该在一个句子中找到该单词并打印包含该关键字的整个句子。整个代码如下所示:

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

int main()
{
    char fileName[128];
    printf("Input your filename (end with .txt):");
    gets(fileName);

    FILE *filePointer = NULL;
    char text1[128];
    char word1[128];
    filePointer = fopen(fileName, "a");

    if(filePointer == NULL)
    {
        printf("Cannot open file!");
        exit(EXIT_FAILURE);
    }
    else{
        printf("Input your sentence: ");
        while (fgets(text1, 127, stdin) != NULL && strncmp(text1, "END\n", 5) != 0){
            printf("Input your sentence: ");
            fprintf(filePointer, "%s", text1);
        }

        int line_num = 1;
        int find_result = 0;
        char text2[128];

        filePointer = fopen(fileName, "r");

        printf("Input keyword you're looking for: ");
        gets(word1);

        while(fgets(text2, 127, filePointer) != NULL) {
            if((strstr(text2, word1)) != NULL) {
                printf("A match found on line: %d\n", line_num);
                printf("\n%s\n", tekst2);
                find_result++;
            }
            line_num++;
        }

        if(find_result == 0) {
            printf("\nSorry, couldn't find a match.\n");
        }

        if(filePointer) {
            fclose(filePointer);
        }

        return(0);
    }
}

一切正常,但问题出在这里:

        int line_num = 1;
        int find_result = 0;
        char text2[128];

        filePointer = fopen(fileName, "r");

        printf("Input keyword you're looking for: ");
        gets(word1);

        while(fgets(text2, 127, filePointer) != NULL) {
            if((strstr(text2, rijec)) != NULL) {
                printf("A match found on line: %d\n", line_num);
                printf("\n%s\n", text2);
                find_result++;
            }
            line_num++;
        }

我是C编程的新手,所以我不确定这个漏洞在哪里。我知道它应该在理论上起作用。它显然不应该返回结果。

1 个答案:

答案 0 :(得分:1)

在重新打开读取之前,您需要在写入之后fclose()文件。

if (fclose(filePointer) != 0)
{
  fputs("The sky is falling.", stderr);
  return 1;
}

filePointer = fopen(fileName, "r");