#include #include #include #include /* Napisz funkcje, ktora majac plik tekstowy i litere (char) zwroci liczbe slow zaczynajacych sie na ta litere (bez względu na wielkosc litery). Przyklad: dla pliku o zawartosci 'ala ma kota a kot' dla 'a' i 'k' wynik to 2, a dla 'm' 1 */ int countWordsStartingWithLetter(FILE *file, char letter) { int count = 0; char word[100]; // Maksymalna dlugosc slowa to 100 znakow //fscanf jest oczywiscie jedynie jedna z mozliwosci, alternatywnie mozna tu uzyc fgetc, getline, strtok, itp. while (fscanf(file, "%s", word) != EOF) { if (tolower(word[0]) == tolower(letter)) { //Sprawdz czy slowo zaczyna sie na dana literę (ignoruj wielkosc liter) count++; } } return count; } int countWordsStartingWithLetterAlternativeVersion(FILE *file, char letter) { rewind(file); // Przesuniecie wskaznika pliku na poczatek (niezbedne jesli wywolujemy ta funkcje po countWordsStartingWithLetter) char *line = NULL; size_t len = 0; char *word; int count = 0; while (getline(&line, &len, file) != -1) { word = strtok(line, " \t\n"); //dzielimy string lini na wyrazy while (word != NULL) { if (tolower(word[0]) == tolower(letter)) { count++; } word = strtok(NULL, " \t\n"); } } free(line); return count; } //bonus: uzycie argc do obslugi parametrow z CLI // Program ten nalezy oczywiscie wywolac z poziomu CLI a nie z CodeBlocks // np. ./zad3 /tmp/ala.txt a int main(int argc, char *argv[]) { if (argc != 3) { printf("Uzyj: %s [nazwa_pliku] [litera]\n", argv[0]); return 1; } //argv[0] to nazwa programu FILE *file = fopen(argv[1], "r"); if (file == NULL) { printf("Nie mozna otworzyc pliku.\n"); return 1; } char letter = argv[2][0]; // Pobierz pierwszy znak jako litere int wordCount = countWordsStartingWithLetter(file, letter); printf("Liczba slow zaczynajacych sie na litere '%c' to: %d\n", letter, wordCount); wordCount = countWordsStartingWithLetterAlternativeVersion(file, letter); printf("Liczba slow zaczynajacych sie na litere '%c' to: %d\n", letter, wordCount); fclose(file); return 0; }