首页 > 解决方案 > 在文件中搜索文本

问题描述

我写了这个但它没有用:我有一个名为contact.txt的文件,我有一些文本,我如何在文件中搜索文本,如果匹配应该打印出c中的文本

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

int main()
{
    char don[150];
    int tr,y;
    FILE *efiom;

    //this is the input of don blah blah blah
    printf("Enter a search term:\n");
    scanf("%s",&don);

    //this is for the reading of the file
    efiom =fopen("efiom.txt","r");
    char go[500];

    //OMO i don't know what is happeing is this my code 
    while(!feof(efiom))
    {
       // this is the solution for the array stuff
       void *reader = go;
       tr = strcmp(don,reader);
       fgets(go, 500 ,efiom);
    }

    // my if statement
    if(tr == 0)
    {
         printf("true\n");
    }
    else
    {
        printf("false\n");
    }
    fclose(efiom);
    return 0;
}

标签: c

解决方案


只需使用以下功能string.h

char * strstr (char * str1, const char * str2 );

返回指向 str1 中第一次出现 str2 的指针,如果 str2 不是 str1 的一部分,则返回空指针。

匹配过程不包括终止的空字符,但它会停在那里。

将文件读入一个字符串 ( char*)。你可以使用这个:

    FILE* fh = fopen(filename, "r");
    char* result = NULL;

    if (fh != NULL) {
        size_t size = 1;

        while (getc(fh) != EOF) {
            size++;
        }

        result  = (char*) malloc(sizeof(char) * size);
        fseek(fh, 0, SEEK_SET); //Reset file pointer to begin

        for (size_t i = 0; i < size - 1; i++) {
            result[i] = (char) getc(fh);
        }

        result[size - 1] = '\0';
        fclose(fh);
    }

推荐阅读