搜索文件中的文本

时间:2019-03-07 11:20:32

标签: c

我写了这个,但是没有用: 我有一个名为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;
}

1 个答案:

答案 0 :(得分:1)

只需使用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);
    }