Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search string in file (C)

So my code isn't working...

test.c:27: warning: passing argument 1 of ‘search’ from incompatible pointer type

which is the fgets line.

My code opens a file, reads the file line by line, and I'm trying to create a "search" function that will return a value that indicates whether that string is found on that line of the file.

My ultimate goal is to achieve a search and replace program. But one step at a time eh? this is what I have so far:

#include <stdio.h>
#include <string.h>

int search(const char *content[], const char *search_term)
{
    int t;

    for(t=0; content[t]; ++t){
        if(!strcmp(content[t], search_term)){
            return t; // found
        }
    }
    return 0; // not found
}


int main(int argc, char *argv[])
{
    FILE *file;
    char line[BUFSIZ];
    int linenumber=0;
    char term[20] = "hello world";

    file = fopen(argv[1], "r");
    if(file != NULL){
        while(fgets(line, sizeof(line), file)){
            if(search(line, term) != -1){
                printf("Search Term Found!!\n");
            }
            ++linenumber;
        }
    }       
    else{
        perror(argv[1]); 
    }

    fclose(file);
    return 0;
}
like image 893
chutsu Avatar asked Apr 28 '26 09:04

chutsu


1 Answers

Change

int search(const char *content[], const char *search_term)

to

int search(const char content[], const char *search_term)

EDIT:

Also change:

if(!strcmp(content[t], search_term)){

to

if(!strcmp(&content[t], search_term)){

or

if(!strcmp(content + t, search_term)){

Since you are using strcmp to find the match, you'll not be able to find all occurrences of the search string the the file. You'll find only those lines that end in the search_string.

Example: your search string is "hello world" and say the file has 2 lines:

I wrote hello world
hello world is good

In this case your program will be able to find only the 1st occurrence and not the 2nd.

Even for this match to be found there are some more changes needed to your code:

The string read by fgets has a trailing newline, you'll have to get rid of it like:

while(fgets(line, sizeof(line), file)){
  line[strlen(line)-1] = 0;

Also when the search fails you are returning 0, which should be changed to -1.

like image 106
codaddict Avatar answered Apr 29 '26 22:04

codaddict