2025-11-03 19:35:58 +01:00

54 lines
1.4 KiB
C

#include "input.h"
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.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)
{
printf("Error! File cannot be opened!\n");
return EXIT_FAILURE;
}
unsigned int count = 0;
char line[MAX_LINE_LEN];
const char *delimiter = " ,;.\n";
while (count < maxWordCount && fgets(line, MAX_LINE_LEN, file) != NULL)
{
char *token = strtok(line, delimiter); //Teilt die Zeile nach den Trennzeichen auf
while (token != NULL && count < maxWordCount)
{
strncpy(words[count], token, MAX_WORD_LEN - 1); //Kopieren des Wortes in dasd Array words
words[count][MAX_WORD_LEN - 1] = '\0'; //Händisches Einfügen des Null-Termminators, da dieser nicht automatisch eingefügt wird
toUpperCase(words[count]); //Umwandeln der Kleinbuchstaben in Großbuchstaben
count++;
token = strtok(NULL, delimiter);
}
}
printf("Total words read: %d\n", count);
return count;
}
void toUpperCase(char *str)
{
for (int i = 0; str[i] != '\0'; i++)
{
str[i] = toupper(str[i]);
}
}