generated from freudenreichan/info2Praktikum-Wortsalat
feat(input): implement file parsing for word list
This commit is contained in:
1 parent
1a78ffca7d
commit
2b20d87350
1 file changed
+40
-2
+40
-2
@@ -2,11 +2,49 @@
|
||||
#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 a single word from file and store it in buffer.
|
||||
Returns the length of the word, or 0 if no more words are available (EOF).
|
||||
*/
|
||||
static int readSingleWord(FILE *file, char buffer[MAX_WORD_LEN])
|
||||
{
|
||||
int len = 0;
|
||||
int c;
|
||||
|
||||
//clear leading seperators
|
||||
while((c = fgetc(file)) != EOF && (c == ',' || c == ';' || c == ' ' || c == '\n')) {}
|
||||
|
||||
//check for empty file
|
||||
if(c == EOF)
|
||||
return 0;
|
||||
|
||||
|
||||
//read word
|
||||
do
|
||||
{
|
||||
if(len < MAX_WORD_LEN - 1) // -1 to leave space for '\0'
|
||||
{
|
||||
buffer[len] = toupper((unsigned char)c);
|
||||
len++;
|
||||
}
|
||||
c = fgetc(file);
|
||||
}
|
||||
while(c != EOF && !(c == ',' || c == ';' || c == ' ' || c == '\n'));
|
||||
|
||||
//append string end-delimiter
|
||||
buffer[len] = '\0'; // '\0' marks the end of a string, we need to apend it for strcpy
|
||||
return len;
|
||||
}
|
||||
|
||||
// Read words from file and store in 'words' array
|
||||
int readWords(FILE *file, char words[][MAX_WORD_LEN], unsigned int maxWordCount)
|
||||
{
|
||||
char buffer[MAX_WORD_LEN];
|
||||
unsigned int wordCount = 0;
|
||||
int len;
|
||||
|
||||
while(wordCount < maxWordCount && (len = readSingleWord(file, buffer)) > 0)
|
||||
strcpy(words[wordCount++], buffer);
|
||||
|
||||
return wordCount;
|
||||
}
|
||||
Reference in new issue
Block a user