2025-11-05 19:32:37 +01:00

60 lines
1.9 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)
{
if(file == NULL) {
return 0;
}
int wordCount = 0;
char buffer[1024]; // Buffer for reading lines
// Read file line by line
while(fgets(buffer, sizeof(buffer), file) != NULL && wordCount < maxWordCount) {
// Process each character in the line
char currentWord[MAX_WORD_LEN];
int wordIndex = 0;
for(int i = 0; buffer[i] != '\0'; i++) {
char c = buffer[i];
// Check if character is a letter
if(isalpha(c)) {
// Convert to uppercase and add to current word
if(wordIndex < MAX_WORD_LEN - 1) {
currentWord[wordIndex++] = toupper(c);
}
}
else {
// Non-letter character = word delimiter
if(wordIndex > 0) {
// We have a complete word
currentWord[wordIndex] = '\0';
strcpy(words[wordCount], currentWord);
wordCount++;
wordIndex = 0;
// Check if we've reached max word count
if(wordCount >= maxWordCount) {
return wordCount;
}
}
}
}
// Handle last word in line if it doesn't end with delimiter
if(wordIndex > 0 && wordCount < maxWordCount) {
currentWord[wordIndex] = '\0';
strcpy(words[wordCount], currentWord);
wordCount++;
}
}
return wordCount;
}