Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,880 questions

51,806 answers

573 users

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

...