在文件中搜索文字

  • 本文关键字:文字 搜索 文件 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("truen");
    }
    else
    {
        printf("falsen");
    }
    fclose(efiom);
    return 0;
}

只需从 string.h中使用此功能:

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

返回一个指针,指向str1中str2的首次出现,如果str2不属于str1。

匹配过程不包括终止的null-character,但它停止了。

将文件读取到一个字符串(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] = '';
        fclose(fh);
    }

最新更新