48 lines
1.5 KiB
C
48 lines
1.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
|
|
int readWords(FILE *file, char words[][MAX_WORD_LEN], unsigned int maxWordCount)
|
|
{
|
|
char line[MAX_LINE_LEN];
|
|
int word_count=0;
|
|
|
|
//Öffnen der Textdatei
|
|
if (file == 0){
|
|
perror("Fehler beim Öffnen der Datei");
|
|
return 1;
|
|
}
|
|
|
|
//Einlesen der Datei Zeile für Zeile
|
|
while (fgets(line, sizeof(line), file)){
|
|
char *token = strtok(line, " ,;\n");
|
|
//Extrahieren von jedem 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] = '\n';
|
|
}
|
|
//Speichere das Wort im Array, falls es nicht leer ist
|
|
if (len > 0){
|
|
//Wandel 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;
|
|
} |