input.c Funktion hergestellt
This commit is contained in:
parent
f398d5b87a
commit
821746b8e3
@ -1,6 +1,6 @@
|
|||||||
#include "input.h"
|
#include "input.h"
|
||||||
|
#include "ctype.h"
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
#include <ctype.h>
|
|
||||||
|
|
||||||
// TODO:
|
// TODO:
|
||||||
// eine Funktion implementieren, die ein einzelnes Wort aus einer Textdatei (words.txt) einliest und als C-String zurückgibt.
|
// eine Funktion implementieren, die ein einzelnes Wort aus einer Textdatei (words.txt) einliest und als C-String zurückgibt.
|
||||||
@ -8,5 +8,42 @@
|
|||||||
// Read words from file and store in 'words' array
|
// Read words from file and store in 'words' array
|
||||||
int readWords(FILE *file, char words[][MAX_WORD_LEN], unsigned int maxWordCount)
|
int readWords(FILE *file, char words[][MAX_WORD_LEN], unsigned int maxWordCount)
|
||||||
{
|
{
|
||||||
|
char line[MAX_LINE_LEN];
|
||||||
|
int word_count = 0;
|
||||||
|
|
||||||
|
// Öffne die Textdatei (Hinweis: Die Datei wird bereits in der Main geöffnet und als Parameter übergeben)
|
||||||
|
if (file == NULL) {
|
||||||
|
perror("Fehler beim Öffnen der Datei");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lese die Datei Zeile für Zeile
|
||||||
|
while (fgets(line, sizeof(line), file)) {
|
||||||
|
char *token = strtok(line, " ,;\n");
|
||||||
|
// Extrahiere jedes 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] = '\0';
|
||||||
|
}
|
||||||
|
// Speichere das Wort im Array, falls es nicht leer ist
|
||||||
|
if (len > 0) {
|
||||||
|
// Wandelt 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;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
|
||||||
Loading…
x
Reference in New Issue
Block a user