53 lines
1.7 KiB
C

#include "input.h"
#include <string.h>
#include <ctype.h>
#include <stdio.h>
// TODO: | VERSION: Erfolgreicher Test 1,2 & 3
// eine Funktion implementieren, die ein einzelnes Wort aus einer Textdatei (words.txt) einliest und als C-String zurückgibt.
int readWords(FILE *file, char words[][MAX_WORD_LEN], unsigned int maxWordCount)
{
unsigned int count = 0;
int c;
unsigned int idx = 0;
if (!file) return 0; //Wenn keine file gefunden oder geöffnet wurde
//scannt jedes zeichen in der file durch bis zum end of file oder bis es genug wörter hat
while ((c = fgetc(file)) != EOF && count < maxWordCount)
{
if (isalpha((unsigned char)c))// prüft ob das zeichen ein buchstabe ist (also kein komma oder leerzeichen usw)
{
//macht die buchstaben zu Großbuchstaben und schreibt sie ins array (toupper)
//prüft ob das wort kurz genug ist
if (idx < MAX_WORD_LEN - 1)
{
words[count][idx++] = (char) toupper((unsigned char)c);
} else
{
// word too long: schneidet das ende vom wort ab bis es reinpasst
idx = MAX_WORD_LEN - 1;
}
} else // bei leerzeichen, komma usw
{
if (idx > 0) //wort endet -> \0 ;stellt den idx wieder auf 0; neues wort beginnt -> count++
{
words[count][idx] = '\0';
count++;
idx = 0;
}
// skip consecutive delimiters
}
}
//Erkennung vom Ende der file wenn das letze wort endet und wort counten
if (idx > 0 && count < maxWordCount) {
words[count][idx] = '\0';
count++;
}
return count;
}