簡體   English   中英

搜索文件中的文本

[英]Searching text in the file

我寫了這個,但是沒用:我有一個名為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;
}

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM