Использование структуры и динамически выделяемой памяти для записи всех строк из текстового файла в C - PullRequest
0 голосов
/ 26 апреля 2020

Я написал программу на C для представления викторины. Каждый вопрос представляет собой отдельную строку текстового файла. Я использую структуру для представления массива вопросов. Он начинается с ввода пользовательского ввода, а затем подсчитывает количество строк текста в файле. Затем он выделил объем памяти, необходимый для структур, перед чтением каждой строки файла в структуру. Когда я распечатываю элементы в структуре, она выводит 20 строк ошибок вместо значений файла. Что я делаю неправильно? Я включил скриншот некоторых строк файла также.

enter image description here

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#define filepath "Questions_Answers"
#define CAPACITY 120

typedef struct
{
char* questions;
} Lines;

int setupGame(int *difficulty);

int main() {

int difficulty;                                     //Set difficulty out of ten of the quiz
int numberOfLines = 0;                              //Set the number of lines counted in the file initially to zero
int question_length;
char answer[20];
char c;

//Calls setup game function which sets the difficulty
difficulty = setupGame(&difficulty);

FILE* fPointer = fopen(filepath, "r");              //Points to the address of a File not yet known

//If the file has no content, print error and end program
if (fPointer == NULL) {
    perror("Error opening file");
    return -1;
}

// Extract characters from file and store in character c 
for (c = getc(fPointer); c != EOF; c = getc(fPointer)) {
    if (c == '\n') // Increment count if this character is newline 
        numberOfLines++;
}

numberOfLines = numberOfLines + 1;

printf("Number of questions in quiz - %d\n", numberOfLines);

Lines *lines = malloc(sizeof(Lines) * numberOfLines); // allocate memory for questions

for (int i = 0; i < numberOfLines; i++) {

    int lengthOfQuestion = 150;

    lines[i].questions = malloc(sizeof(char) * (lengthOfQuestion + 1));
    fscanf(fPointer, "%s", lines[i].questions);
    printf("%s\n", lines[i].questions);
}

fclose(fPointer);

for (int i = 0; i < numberOfLines; i++) {
    free(lines[i].questions);
    }

free(lines);
return 0;
}

1 Ответ

1 голос
/ 26 апреля 2020

Вам нужно fclose(fPointer);, а затем снова открыть, прежде чем вы хотите получить вопросы из файла.

fclose(fPointer);
fPointer = fopen("input.txt", "r");

fscanf читает слово за словом, а не всю строку. Вы должны использовать fgets() или getline().

Я вижу в вашем коде, вы задаете длину всех вопросов на 150

int lengthOfQuestion = 150;

Так что, я думаю, это проще когда вы объявляете структуру (вы можете использовать указатель, если хотите):

typedef struct
{
    char questions[150];
} Lines;

Вы должны использовать один l oop для хранения и увеличения количества строк. Код будет более читабельным. Например:

char line[150];
lines = malloc(sizeof(Lines));
if(!lines) {// handle the error}
while (fgets(fPointer, sizeof(line), line)) {
    strcpy(lines[numberOfLines].question, line);
    numberOfLines++;
    lines = realloc(lines, sizeof(Lines) * numberOfLines);
    if(!line) {// handle the error}

}
...