2025-10-21 06:58:43 +02:00

58 lines
1.7 KiB
C

#include "input.h"
#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 words from file and store in 'words' array
// int readWords(FILE *file, char words[][MAX_WORD_LEN], unsigned int maxWordCount)
// {
// }
// Đọc danh sách các từ từ tệp và lưu vào mảng 'words'.
// Trả về số lượng từ đã đọc được, hoặc -1 nếu lỗi.
int readWords(FILE *file, char words[][MAX_WORD_LEN], unsigned int maxWordCount)
{
if (file == NULL)
{
fprintf(stderr, "Fehler: Datei ist NULL.\n");
return -1;
}
unsigned int count = 0;
char line[MAX_WORD_LEN + 5]; // thêm chút dư để tránh tràn
// Đọc từng dòng cho đến khi hết file hoặc đạt giới hạn
while (fgets(line, sizeof(line), file) != NULL && count < maxWordCount)
{
// Xóa ký tự xuống dòng '\n' nếu có
line[strcspn(line, "\r\n")] = '\0';
// Bỏ qua dòng trống
if (strlen(line) == 0)
continue;
// Loại bỏ khoảng trắng đầu/cuối (nếu có)
char *start = line;
while (isspace((unsigned char)*start))
start++;
char *end = start + strlen(start) - 1;
while (end > start && isspace((unsigned char)*end))
{
*end = '\0';
end--;
}
// Sao chép an toàn vào mảng words
strncpy(words[count], start, MAX_WORD_LEN - 1);
words[count][MAX_WORD_LEN - 1] = '\0'; // đảm bảo kết thúc chuỗi
count++;
}
return count;
}