generated from freudenreichan/info2Praktikum-Wortsalat
54 lines
1.4 KiB
C
54 lines
1.4 KiB
C
#include "input.h"
|
|
#include <string.h>
|
|
#include <ctype.h>
|
|
#include <stdio.h> //fürs öffnen FILE
|
|
|
|
// TODO:
|
|
// eine Funktion implementieren, die ein einzelnes Wort aus einer Textdatei (words.txt) einliest und als C-String zurückgibt.
|
|
|
|
// Read words from file and store in 'words' array
|
|
|
|
#define MAX_WORD_LENGTH 100 //ka ob man dass muss
|
|
|
|
|
|
int readWords(FILE *file, char words[][MAX_WORD_LEN], unsigned int maxWordCount)
|
|
{
|
|
|
|
FILE *quelle; //Zeiger auf quelle
|
|
|
|
quelle = fopen("words.txt", "r"); //quelle definieren (Datei öffnen)
|
|
|
|
|
|
if (quelle==0) //Dateiöffnen geklappt?
|
|
{
|
|
printf("File not found\n");
|
|
return -1;
|
|
}
|
|
|
|
char speicher[1000]; //speichern einer Zeile
|
|
int anzahlwörter=0;
|
|
|
|
if(fgets(speicher, sizeof(speicher), quelle)==0)
|
|
{
|
|
printf("Datei leer");
|
|
return -1;
|
|
}
|
|
|
|
char *token = strtok(speicher, " \t\n");
|
|
|
|
|
|
while (token != NULL && anzahlwörter < maxWordCount) {
|
|
strncpy(words[anzahlwörter], token, MAX_WORD_LEN - 1);
|
|
words[anzahlwörter][MAX_WORD_LEN - 1] = '\0'; // Sicherheit: String terminieren
|
|
anzahlwörter++;
|
|
token = strtok(NULL, " \t\n"); //NULL, damit nicht mehr Anfangsadresse
|
|
}
|
|
|
|
|
|
|
|
|
|
fclose(quelle); //Datei schließen
|
|
return anzahlwörter; //Funktion gibt Anzahl zurück
|
|
|
|
}
|