cstringfile-processingword-processor

Determine if a file contains a string in C


How can I check if a given FILE* contains a string in C running on Linux (if it matters)?

The string must consist of the whole line it's on. For example, this:

jfjfkjj
string
jfjkfjk

would be true; but this:

jffjknf
fklm...string...lflj
jfjkfnj

wouldn't. I'm essentially looking for an internal alternative to system("grep -x file")


Solution

  • This reads a file line by line and checks if the line matches the string supplied in argument 1 (argv[1]) after every read. If so, it sets the bool infile (bools defined in <stdbool.h>) to true.

    #include <stdbool.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    
    int main(int argc, char **argv[]) {
        char    *filepath = "/path/to/file";
        bool    infile = false;
        char    *line = NULL;
        size_t  len = 0;
        ssize_t read;
    
        FILE    *fp = fopen(filepath, "r");
    
        if (!fp) {
            fprintf(stderr, "Failed to open %s\n", filepath);
            return 1;
        }
    
        while ((read = getline(&line, &len, fp)) != -1) {
            line[strcspn(line, "\n")] = 0;
            if (!strcmp(line, argv[1])) {
                infile = true;
                break;
            }
        }
        fclose(uuidfp);
    
        if (line)
            free(line);
    
        return 0;
    }