How to search for a string in a text file with C

1 Answer

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

#define LINELEN 256

void search_string(const char* filename, const char* needle) {
    char line[LINELEN] = "";
    size_t needlelen = strlen(needle);

    FILE* fp = fopen(filename, "r");

    if (fp == NULL) {
        perror("Error opening file");
        return;
     }
    else {
        while (!feof(fp)) {
            if (fgets(line, LINELEN, fp)) {
                // char *strstr(const char *haystack, const char *needle)
                if (strstr(line, needle)) {
                    puts(line);
                    break;
                }
            }
        }
    }
    
    fclose(fp);
}

int main() {

    char filename[] = "d://abc.php";
    char tofind[] = "__construct";

    search_string(filename, tofind);

    return 0;
}



/*
run:

 public function __construct($user, $content, $url, $datetime)

*/

 



answered May 25, 2024 by avibootz

Related questions

1 answer 106 views
2 answers 187 views
1 answer 206 views
1 answer 216 views
1 answer 172 views
...