2025-10-30 21:20:06 +01:00

54 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) {
if (file == NULL) {
perror("File couldn't be opened");
return 0;
}
// zunächst fehlerhaften String einlesen und in anderem Array
// zwischenspeichern
char line[MAX_LINE_LEN];
char *token;
int wordCount = 0;
while (fgets(line, sizeof(line), file) !=
NULL && // während mit fgets alle Zeichen aus dem file eingelesen
// werden
wordCount < maxWordCount) {
token = strtok(line, " ;,.\n"); // Erstes Wort mit strtok aus dem
// fehlerhaften String herauslösen
while (token != NULL &&
wordCount < maxWordCount) { // while strtok nicht am Ende ist und
// noch Wörter in words passen
for (int i = 0; token[i] != '\0'; i++) {
token[i] = toupper((unsigned char)token[i]);
}
strncpy(words[wordCount], token,
sizeof(words[wordCount]) -
1); // mit strcpy das aktuelle Wort in words kopieren
words[wordCount][sizeof(words[wordCount]) - 1] =
'\0'; // Nullterminator mit sizeof des aktuellen Worts - 1 an Ende des
// Worts setzen
wordCount++; // Nächstes Wort
token = strtok(NULL, " ;,.\n"); // Nächstes Token
}
}
return wordCount; // Anzahl der eingelesenen Wörter
}