Files
info2Praktikum-Wortsalat/Startcode/input.c
T

45 lines
1.2 KiB
C

#include "input.h"
#include <string.h>
#include <ctype.h>
// Liest ein einzelnes Wort aus der Datei in 'buffer' (max. bufferSize Zeichen inkl. '\0')
// Gibt 'buffer' zurück oder NULL, wenn kein Wort mehr vorhanden ist
static char *readWord(FILE *file, char *buffer, unsigned int bufferSize)
{
unsigned int len = 0;
int c = fgetc(file);
// Trennzeichen (Leerzeichen, Komma, Semikolon, Zeilenumbruch, ...) überspringen
while (c != EOF && !isalpha(c))
c = fgetc(file);
// Buchstaben sammeln, bis ein Trennzeichen oder das Dateiende kommt
while (c != EOF && isalpha(c))
{
if (len < bufferSize - 1)
buffer[len++] = toupper(c);
c = fgetc(file);
}
buffer[len] = '\0';
if (len == 0)
return NULL;
return buffer;
}
// Read words from file and store in 'words' array
int readWords(FILE *file, char words[][MAX_WORD_LEN], unsigned int maxWordCount)
{
char word[MAX_WORD_LEN];
unsigned int wordCount = 0;
while (wordCount < maxWordCount && readWord(file, word, MAX_WORD_LEN) != NULL)
{
strncpy(words[wordCount], word, MAX_WORD_LEN - 1);
words[wordCount][MAX_WORD_LEN - 1] = '\0';
wordCount++;
}
return wordCount;
}