How to search for a string in a text file and parse that line 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)) {
                    printf("The line: %s\n", line);
                    char* p = strtok(line, " ,()");
                    while (p != NULL) {
                        printf("%s\n", p);
                        p = strtok(NULL, " ,()");
                    }
                    break;
                }
            }
        }
    }
    
    fclose(fp);
}

int main() {

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

    search_string(filename, tofind);

    return 0;
}



/*
run:

The line: public function __construct($user, $content, $url, $datetime)

public
function
__construct
$user
$content
$url
$datetime

*/

 



answered May 25, 2024 by avibootz

Related questions

...