Log filter

Napisati program koji iz tekstualnog log fajla izdvaja samo linije koje zadovoljavaju tražene kriterijume i ispisuje ih na standardni izlaz.

Ulaz

Program se pokreće komandnom linijom oblika

./logfilter <log_tag> <putanja_do_log_fajla> [<pretraga>]

Izlaz

Na standardni izlaz ispisati sve linije iz fajla koje sadrže zadati log_tag, a ako je prosleđen i <pretraga>, ispisati i linije koje sadrže tu nisku.

U slučaju greške, na standardni izlaz za greške ispisati odgovarajuću poruku i završiti program sa statusom neuspeha (1).

Primer

server.log

[INFO] Server started
[DEBUG] Listening on port 8080
[WARN] Low disk space
[INFO] User login succeeded
[DEBUG] Cache miss for key user:123
[ERROR] Connection timed out
[INFO] Request completed

command line

./logfilter INFO server.log

stdout

[INFO] Server started
[INFO] User login succeeded
[INFO] Request completed

Primer

server.log

[INFO] Server started
[DEBUG] Listening on port 8080
[INFO] Request completed

command line

./logfilter DEBUG server.log started

stdout

[INFO] Server started
[DEBUG] Listening on port 8080

Primer

command line

./logfilter ERROR missing.log

stderr

Error: Could not open file missing.log

Primer

command line

./logfilter INFO

stderr

Error: Invalid number of arguments. 

Rešenje

main.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#define MAX_LINE_LEN 1000

int main(int argc, char *argv[])
{
	if (argc < 3 || argc > 4) {
		fprintf(stderr, "Error: Invalid number of arguments.\n");
		exit(EXIT_FAILURE);
	}

	const char *search_string = NULL;
	if (argc == 4) {
		search_string = argv[3];
	}

	const char *log_tag = argv[1];

	FILE *log_file = fopen(argv[2], "r");
	if (log_file == NULL) {
		fprintf(stderr, "Error: Could not open file %s\n", argv[2]);
		exit(EXIT_FAILURE);
	}	

	char *line = NULL;
	size_t len = 0;
	ssize_t nread;

	while ((nread = getline(&line, &len, log_file)) != -1) {
		if (strstr(line, log_tag) != NULL) {
			printf("%s", line);
		} else if (search_string != NULL && strstr(line, search_string) != NULL) {
			printf("%s", line);
		}
	}

	fclose(log_file);

	exit(EXIT_SUCCESS);
}