【问题标题】:A function to read a text file and transfer that information to a dynamic vector读取文本文件并将该信息传输到动态向量的函数
【发布时间】:2020-06-20 11:55:31
【问题描述】:

创建一个函数来读取文本文件并将其名称传输到结构的动态向量。 我正在读取文件,但屏幕上没有显示任何内容。

typedef struct aluno student;
struct aluno{
       
       char name[50], address[50], number[9];
       int year;enter code here

};

student *lerFicheiroTexto(char *nameFile, int *tam){

        FILE *f1;
        student buffer;
        student *aux;
        student *vetor = NULL;
        f1 = fopen(nameFile, "rt");
        if(f1 == NULL){
            printf("Error opening the file text");
            return NULL;
        }

        
        while(fscanf(f1, "%s %s %d %s", buffer.name, buffer.address, &buffer.year, buffer.number) == 3){
               
                printf("%s\t%s\n%d\n%s\n", buffer.name, buffer.address, buffer.year, buffer.number);
                aux = realloc(vetor, sizeof(student)*(*tam+1));
                  if(aux == NULL){
               //realocation failled
               printf("Reallocation failled. Maintain tam \n");
               (*tam) = 0;
               return NULL;
           }
                  else{
                      
                      vetor = aux;
                      vetor[(*tam)] = buffer;
                  
                  }
                
            (*tam)++;
        }
        
        
        fclose(f1);
        return vetor;
}

【问题讨论】:

  • == 3??有四个格式说明符。
  • 即使是 4 也行不通
  • 调试代码你看到了什么?也就是说,在调试器中运行它。它在哪里失败? fscanf 会返回什么(如果它走得那么远)?您仍然可以进行相当多的基本调试。如果您仍然需要帮助,请提供输入文件数据。
  • 当我调试代码失败时,屏幕上会出现以下消息: Press [Enter] to close the terminal ...
  • 那不是调试。那只是运行代码。调试意味着通过代码跟踪以查看每一行在做什么,并找出问题到底从哪里开始出错。 How to debug small programs

标签: c scanf


【解决方案1】:

我需要你的输入文件来测试这个,但我稍微改变了你的代码。 我也是一名学生,如果我做错了什么,我深表歉意。

据我所知,我相信您的代码可以像这样改进:

结构定义:

typedef struct aluno {
    char name[50], address[50], number[9];
    int year;
} Aluno;

读取文件并构建数组的功能:

Aluno* lerFicheiroTexto(char* nameFile, int tamanho)
{
    FILE* file = fopen(nameFile, "r");

    if (file == NULL) {
        printf("Error opening the file text");
        return NULL;
    }

    Aluno* listaAlunos = malloc(sizeof(Aluno));
    char line[255];
    while (fgets(line, 255, file) != NULL) {
        Aluno currAluno;
        sscanf(line, "%s %s %d %s", currAluno.name, currAluno.address, currAluno.year, currAluno.number);

        listaAlunos[tamanho] = currAluno;

        listaAlunos = realloc(listaAlunos, sizeof(Aluno) * ++tamanho);
    }

    fclose(file);
    return listaAlunos;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-22
    • 1970-01-01
    • 2011-02-05
    • 2020-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多