Anpassung input.c nach Unit Tests

This commit is contained in:
kleinleinta105608 committed 2026-10-30 13:58:13 +01:00
1 parent 9e53289322
commit 852ae19472
1 file changed
+52 -17
+52 -17
View File
@@ -6,37 +6,72 @@
// eine Funktion implementieren, die ein einzelnes Wort aus einer Textdatei (words.txt) einliest und als C-String zurückgibt. // eine Funktion implementieren, die ein einzelnes Wort aus einer Textdatei (words.txt) einliest und als C-String zurückgibt.
char* readSingleWord(FILE *file, char *destination, int maxLen) char* readSingleWord(FILE *file, char *destination, int maxLen)
{ {
char buffer[256]; char buffer[256];
int ch;
// %255s schützt vor Pufferüberläufen des 256-Zeichen-buffers int bufIndex = 0;
if (fscanf(file, "%255s", buffer) == 1)
{
strncpy(destination, buffer, maxLen - 1);
destination[maxLen - 1] = '\0'; // Zwingendes Ende des C-Strings setzen
return destination; // Rückgabe bei Erfolg
}
return NULL; // Rückgabe bei Dateiende
}
// Alle Trennzeichen überspringen, bis ein echter Buchstabe kommt
while ((ch = fgetc(file)) != EOF)
{
// Prüfen der Buchstaben
if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))
{
// Wenn Kleinbuchstabe, in Großbuchstabe umwandeln
if (ch >= 'a' && ch <= 'z')
{
ch = ch - 32;
}
buffer[bufIndex] = ch;
bufIndex++;
break;
}
}
if (ch == EOF)
{
return NULL;
}
// Den Rest des Wortes einlesen (bricht bei Kommas, Leerzeichen etc. ab)
while ((ch = fgetc(file)) != EOF && ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')))
{
if (bufIndex < 255)
{
if (ch >= 'a' && ch <= 'z')
{
ch = ch - 32;
}
buffer[bufIndex] = ch;
bufIndex++;
}
}
// Zwischenspeicher abschließen
buffer[bufIndex] = '\0';
// Sicheres Kopieren in das Ziel-Array
strncpy(destination, buffer, maxLen - 1);
destination[maxLen - 1] = '\0';
return destination;
}
// Read words from file and store in 'words' array // Read words from file and store in 'words' array
int readWords(FILE *file, char words[][MAX_WORD_LEN], unsigned int maxWordCount) int readWords(FILE *file, char words[][MAX_WORD_LEN], unsigned int maxWordCount)
{ {
unsigned int count = 0; unsigned int count = 0;
// Schleife läuft, solange noch Platz im Array ist
while (count < maxWordCount) while (count < maxWordCount)
{ {
// Aufruf Hilfsfunktion mit Arraygröße als Parameter
if (readSingleWord(file, words[count], MAX_WORD_LEN) != NULL) if (readSingleWord(file, words[count], MAX_WORD_LEN) != NULL)
{ {
if (strlen(words[count]) > 0) if (strlen(words[count]) > 0) // Prüfen, ob das Wort nicht leer ist
{ {
count++; count++; //nächstes Wort
} }
} }
else else
{ {
break; // Ende der Datei erreicht break; // Bei Dateiende wird die Schleife abgebrochen
} }
} }
return count; return count;