50 lines
1.7 KiB
C
50 lines
1.7 KiB
C
#include "input.h"
|
|
#include "ctype.h"
|
|
#include <string.h>
|
|
|
|
// TODO:
|
|
// eine Funktion implementieren, die ein einzelnes Wort aus einer Textdatei (words.txt) einliest und als C-String zurückgibt.
|
|
|
|
// Read words from file and store in 'words' array
|
|
int readWords(FILE *file, char words[][MAX_WORD_LEN], unsigned int maxWordCount)
|
|
{
|
|
char line[MAX_LINE_LEN];
|
|
int word_count = 0;
|
|
|
|
// Öffne die Textdatei (Hinweis: Die Datei wird bereits in der Main geöffnet und als Parameter übergeben)
|
|
if (file == NULL) {
|
|
perror("Fehler beim Öffnen der Datei");
|
|
return 1;
|
|
}
|
|
|
|
// Lese die Datei Zeile für Zeile
|
|
while (fgets(line, sizeof(line), file)) {
|
|
char *token = strtok(line, " ,;\n");
|
|
// Extrahiere jedes Wort
|
|
while (token != NULL && word_count < maxWordCount) {
|
|
// Entferne führende und nachfolgende Leerzeichen
|
|
while (isspace((unsigned char) *token)) {
|
|
token++;
|
|
}
|
|
size_t len = strlen(token);
|
|
while (len > 0 && isspace((unsigned char) token[len - 1])) {
|
|
token[--len] = '\0';
|
|
}
|
|
// Speichere das Wort im Array, falls es nicht leer ist
|
|
if (len > 0) {
|
|
// Wandelt das Wort in Großbuchstaben um
|
|
for (size_t i = 0; i < len; i++) {
|
|
token[i] = toupper((unsigned char)token[i]);
|
|
}
|
|
strncpy(words[word_count], token, MAX_WORD_LEN - 1);
|
|
words[word_count][MAX_WORD_LEN - 1] = '\0';
|
|
word_count++;
|
|
}
|
|
// Nächstes Wort
|
|
token = strtok(NULL, " ,;\n");
|
|
}
|
|
}
|
|
return word_count;
|
|
}
|
|
|