72 lines
2.1 KiB
C

//erstellt von Harun Faizi am 01.11.2025
#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.
/* Liest Wörter aus words.txt und speichert sie in ein 2D-Array "words"
Trennzeichen: Komma, Semikolon, Leerzeichen und Zeilenumbruch
file: geöffnete Datei (words.txt)
words: 2D-Array zu Speicherung der Wörter
maxWordCount: maximale Anzahl an Wörter, die eingelesen dürfen
Rückgabe: Anzahl der eingelesen Wörter (0 falls nichts gelesen oder Fehler)
*/
// Read words from file and store in 'words' array
int readWords(FILE *file, char words[][MAX_WORD_LEN], unsigned int maxWordCount)
{
if (file == 0)
return 0; //Sicherheitsprüfung
char line[MAX_LINE_LEN]; // Puffer für eine Zeile aus Datei
unsigned int wordCount = 0; // zählt wie viele Wörter gefunden wurden
//Lese Datei Zeile für Zeile
while(fgets(line, sizeof(line), file) != NULL)
{
// Zerlege die Datei in einzelne Wörter
char *token = strtok(line, ",;\n\t");
while (token != NULL && wordCount < maxWordCount)
{
//aktuelles Wort in Array kopieren
strncpy(words[wordCount], token, MAX_WORD_LEN -1);
words[wordCount][MAX_WORD_LEN -1] = '\0';
// Entferne führende Leerzeichen
int start = 0;
while (words[wordCount][start] == ' ')
start++;
if (start > 0)
memmove(words[wordCount], words[wordCount] + start, strlen(words[wordCount]) - start + 1);
// Entferne nachfolgende Leerzeichen
int end = strlen(words[wordCount]) - 1;
while (end >= 0 && words[wordCount][end] == ' ')
{
words[wordCount][end] = '\0';
end--;
}
wordCount++;
token = strtok(NULL, ",;\n");
}
// Wenn max Wortzahl erreicht ist abbrechen!
if (wordCount >= maxWordCount)
break;
}
return wordCount;
}