generated from freudenreichan/info2Praktikum-Wortsalat
50 lines
1.2 KiB
C
50 lines
1.2 KiB
C
#include "input.h"
|
|
#include <string.h>
|
|
#include <ctype.h>
|
|
|
|
/*
|
|
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;
|
|
} |