39 lines
2.2 KiB
C
39 lines
2.2 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <ctype.h>
|
|
#include "input.h"
|
|
|
|
|
|
// TODO:
|
|
// eine Funktion implementieren, die ein einzelnes Wort aus einer Textdatei (words.txt) einliest und als C-String zurückgibt.
|
|
|
|
|
|
int readWords(FILE *file, char words[][MAX_WORD_LEN], unsigned int maxWordCount)
|
|
{
|
|
|
|
unsigned int count = 0; // wie viele Wörter bisher gespeichert wurden
|
|
char line[MAX_LINE_LEN]; // Puffer für EINE gelesene Textzeile
|
|
|
|
while(fgets(line, sizeof(line), file)!= NULL && count < maxWordCount) //fgets liest eine komplette Zeile wenn es noch eine Zeile gibt und noch Platz für mehr Wörter ist
|
|
{
|
|
const char *delims = "\t\n\r ,;"; //Liste der Trenner (z.B. Komma)
|
|
char *token = strtok(line, delims); //strok sucht in line das erste Wort, indem es an Trennzeichen teilt. Wenn kein Wort gefunden, wird NULL zurück gegeben
|
|
|
|
|
|
while (token != NULL && count < maxWordCount) //Solange es noch ein Wort (token) gibt und noch Platz in words ist
|
|
{
|
|
for(unsigned int i = 0; token[i] != '\0'; i++)
|
|
{
|
|
token[i] = toupper((unsigned char)token[i]); //toupper macht jeden Buchstaben groß.
|
|
}
|
|
strncpy(words[count], token, MAX_WORD_LEN -1); //Kopiert das Wort in den nächsten freien Slot words[count].
|
|
words[count][MAX_WORD_LEN -1] = '\0';
|
|
count++; //Wir habenein Wort abgespeichert count + 1
|
|
token = strtok(NULL, delims); //hier
|
|
|
|
}
|
|
}
|
|
return count;
|
|
}
|