54 lines
1.8 KiB
C

#include "input.h"
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
// TODO:
// eine Funktion implementieren, die ein einzelnes Wort aus einer Textdatei (words.txt) einliest und als C-String zurückgibt.
char* readWord(FILE *file)
{
char word[MAX_WORD_LEN]; // Puffer für Wort
int index = 0; // Position im Puffer
int c; // Variable für jedes gelesene Zeichen
// Whitespace und Delimiters überspringen
while ((c = fgetc(file)) != EOF && (isspace((unsigned char)c) || c == ',' || c == ';' || c == '.'));
if (c == EOF) {
return NULL;
}
// Buchstaben einlesen bis nächstes whitespace/Delimiter/EOF
while (c != EOF && !isspace((unsigned char)c) && c != ',' && c != ';' && c != '.' && index < MAX_WORD_LEN - 1) //-1 wegen Nullterminator
{
word[index++] = (char)toupper((unsigned char)c); // Konvertiere zu Großbuchstaben
c = fgetc(file);
}
word[index] = '\0'; // Nullterminator (= Ende String)
if (index == 0) {
return NULL;
}
return strdup(word); // Rückgabe string, dynamisch allokiert da Zeiger auf lokalen Puffer zurückgegeben
}
// Read words from file and store in 'words' array
int readWords(FILE *file, char words[][MAX_WORD_LEN], unsigned int maxWordCount)
{
unsigned int count = 0;
while(count < maxWordCount && !feof(file))
{
char *word = readWord(file);
if(word != NULL)
{
strncpy(words[count], word, MAX_WORD_LEN - 1); // Wort in Array kopieren
words[count][MAX_WORD_LEN - 1] = '\0'; // Sicherstellen, dass String nullterminiert ist
free(word); // Dynamisch allokierten Speicher freigeben
count++;
}
}
return count; // Anzahl gelesene Wörter zurückgeben
}