forked from freudenreichan/info2Praktikum-Wortsalat
69 lines
2.5 KiB
C
69 lines
2.5 KiB
C
#include "input.h"
|
|
#include <string.h>
|
|
#include <ctype.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
|
|
|
|
// Liest Wörter aus einer Textdatei und speichert sie im Array.
|
|
int readWords(FILE *file, char words[][MAX_WORD_LEN], unsigned int maxWordCount)
|
|
{
|
|
// Prüft, ob die Eingaben gültig sind.
|
|
if (file == NULL || words == NULL || maxWordCount == 0) {
|
|
return 0;
|
|
}
|
|
|
|
unsigned int count = 0;
|
|
char currentWord[MAX_WORD_LEN];
|
|
size_t length = 0;
|
|
int tooLong = 0;
|
|
int ch;
|
|
|
|
while (count < maxWordCount && (ch = fgetc(file)) != EOF) {
|
|
// fgetc(file) liest jeweils ein Zeichen aus der Datei.
|
|
|
|
if (ch == ',' || ch == ';' || isspace((unsigned char)ch)) {
|
|
// isspace() erkennt Leerraumzeichen wie Leerzeichen und Zeilenumbrüche. Kommas und Semikolons werden separat geprüft.
|
|
|
|
// Speichert das Wort, wenn es nicht leer und nicht zu lang ist.
|
|
if (length > 0 && !tooLong) {
|
|
currentWord[length] = '\0';
|
|
strncpy(words[count], currentWord, MAX_WORD_LEN);
|
|
// strncpy() kopiert das fertige Wort mit einer festgelegten maximalen Länge in das Zielarray.
|
|
count++; // Erhöht die Anzahl der gespeicherten Wörter.
|
|
}
|
|
|
|
// Setzt die Variablen für das nächste Wort zurück.
|
|
length = 0;
|
|
tooLong = 0;
|
|
}
|
|
else if (!tooLong) {
|
|
|
|
// Prüft, ob noch Platz für das Zeichen und '\0' vorhanden ist.
|
|
if (length < MAX_WORD_LEN - 1) {
|
|
// toupper() wandelt Kleinbuchstaben in Großbuchstaben um.
|
|
// MAX_WORD_LEN - 1 Lässt Platz für '\0', das das Ende eines C-Strings kennzeichnet und verhindert, dass über den Wortpuffer hinausgeschrieben wird.
|
|
currentWord[length] = (char)toupper((unsigned char)ch);
|
|
length++;
|
|
}
|
|
else {
|
|
// Überspringt das Wort, wenn es zu lang ist.
|
|
tooLong = 1;
|
|
length = 0;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Speichert das letzte Wort, falls die Datei ohne Trennzeichen endet.
|
|
if (count < maxWordCount && length > 0 && !tooLong) {
|
|
currentWord[length] = '\0';
|
|
strncpy(words[count], currentWord, MAX_WORD_LEN);
|
|
count++;
|
|
}
|
|
|
|
// Gibt die Anzahl der gespeicherten Wörter zurück.
|
|
return (int)count;
|
|
|
|
} |