0

I wrote this but it didn't work: I have a file named contact.txt, i have some text in, how can i search for a text in the file and if it matches should print out that text in 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;
}
caxapexac
  • 781
  • 9
  • 24
Curtis Crentsil
  • 459
  • 6
  • 20
  • 2
    It "didn't work" how? Note: see [Why is `while ( !feof (file) )` always wrong?](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) Better as `while(fgets(go, 500 ,efiom) != NULL) { /*...*/ };` – Weather Vane Mar 07 '19 at 11:25
  • Also `fgets` retains any trailing newline so you won't get a string match. Please see [Removing trailing newline character from fgets() input](https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input/28462221#28462221). – Weather Vane Mar 07 '19 at 11:29

1 Answers1

1

Just use this function from string.h:

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

Returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1.

The matching process does not include the terminating null-characters, but it stops there.

Read file to one string (char*). You can use this:

    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);
    }
Community
  • 1
  • 1
Igor Galczak
  • 142
  • 6