Files
Info2_Pr_Wortsalat/Startcode/input.c
T
2026-10-19 17:16:53 +02:00

46 lines
1.6 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.
int readWords(FILE *file, char words[][MAX_WORD_LEN], unsigned int maxWordCount) // Read words from file and
// store in 'words' array
{
int count = 0; // zaehlt die gespeicherten Woerter
if(file == NULL || maxWordCount == 0) // keine Datei oder kein Platz
{
return 0; //Raus aus dem Programm und Abbruch
}
char line[MAX_LINE_LEN]; // Puffer fuer eine ganze Zeile 1024
while(fgets(line, MAX_LINE_LEN, file) != NULL) // jede Zeile lesen
{
char *word = strtok(line, ",; \t\r\n"); // erstes Wort der Zeile
while(word != NULL && count < maxWordCount) // jedes Wort der Zeile
{
if(strlen(word) != 0 && strlen(word) < MAX_WORD_LEN) // Wort gueltig?
{
strncpy(words[count], word, MAX_WORD_LEN -1); // Wort sicher ins naechste Fach kopieren
words[count][MAX_WORD_LEN -1] = '\0'; // String sicher mit '\0' abschliessen
for(int i = 0; words[count][i] != '\0'; i++)
{
words[count][i] = toupper(words[count][i]);
}
count++; // ein Wort mehr gespeichert
}
word = strtok(NULL, " ,; \t\n\r"); // naechstes Wort holen
}
}
return count; // Anzahl der gespeicherten Woerter zurueckgeben
}