Files
info2Praktikum-Wortsalat/Startcode/input.c
T

55 lines
1.4 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 || words == NULL || maxWordCount == 0) {
return 0;
}
unsigned int count = 0;
char currentWord[MAX_WORD_LEN];
size_t length = 0;
int tooLong = 0;
int ch;
while (count < maxWordCount && (ch = fgetc(file)) != EOF) {
if (ch == ',' || ch == ';' || isspace((unsigned char)ch)) {
if (length > 0 && !tooLong) {
currentWord[length] = '\0';
strncpy(words[count], currentWord, MAX_WORD_LEN);
count++;
}
length = 0;
tooLong = 0;
}
else if (!tooLong) {
if (length < MAX_WORD_LEN - 1) {
currentWord[length] = (char)toupper((unsigned char)ch);
length++;
}
else {
tooLong = 1;
length = 0;
}
}
}
if (count < maxWordCount && length > 0 && !tooLong) {
currentWord[length] = '\0';
strncpy(words[count], currentWord, MAX_WORD_LEN);
count++;
}
return (int)count;
}