How to print the log line containing a specific date from a text block in C

1 Answer

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

void printLogByDate(const char *logs, const char *targetDate) {
    char *copy = strdup(logs);   // make a modifiable copy
    char *line = strtok(copy, "\n");

    while (line != NULL) {
        if (strstr(line, targetDate) != NULL) {
            printf("%s\n", line);
            free(copy);
            return;   // stop after first match
        }
        line = strtok(NULL, "\n");
    }

    printf("Date not found.\n");
    
    free(copy);
}

int main(void) {
    const char *logs =
        "01/12/2023 - Log entry one.\n"
        "17/03/2021 - Log entry two.\n"
        "29/07/2019 - Log entry three.\n"
        "05/11/2024 - Log entry four.\n"
        "22/08/2020 - Log entry five.\n"
        "14/02/2018 - Log entry six.\n"
        "30/09/2022 - Log entry seven.\n"
        "11/06/2017 - Log entry eight.\n"
        "03/04/2025 - Log entry nine.\n"
        "26/01/2016 - Log entry ten.\n";

    printLogByDate(logs, "05/11/2024");
    
    return 0;
}



/*
run:

05/11/2024 - Log entry four.

*/

 



answered 12 hours ago by avibootz

Related questions

...