Broj linija

Napisati program koji broji koliko se linija nalazi u zadatoj tekstualnoj datoteci.

Ulaz

Program se pokreće sa jednim argumentom komandne linije:

./nol <putanja_do_fajla>

Gde <putanja_do_fajla> označava postojeću tekstualnu datoteku.

Izlaz

Na standardni izlaz ispisati poruku oblika Number of lines: <X> praćenu novim redom, gde je <X> broj linija.

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

Primer

primer.txt

alpha
beta
gamma

command line

./nol primer.txt

stdout

Number of lines: 3

Primer

command line

./nol nepostojeci_fajl.txt

stderr

Error: Could not open file nepostojeci_fajl.txt

Primer

command line

./nol

stderr

Error: Invalid number of arguments.

Rešenje

main.c

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

int main(int argc, char *argv[])
{
	if (argc != 2) {
		fprintf(stderr, "Error: Invalid number of arguments.\n");
		exit(EXIT_FAILURE);
	}

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

	int line_count = 0;

	int read = 0;
	char ch;
	while ((ch = fgetc(file)) != EOF) {
		read = 1;
		if (ch == '\n') {
			line_count++;
		}
	}

	if (read) {
		line_count++;
	}

	printf("Number of lines: %d\n", line_count);

	fclose(file);

	exit(EXIT_SUCCESS);
}