无法从C中的文本文件中读取结构

时间:2017-01-04 14:08:16

标签: c file struct

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
    int id;
    char* name;
    float weight;
  } Person;





int main()
{
    Person *person=malloc(10*sizeof(Person));
    int i=0;
    char row[20];
    FILE *input=fopen("input.txt","r+");

    while(fscanf( input, "%s", &row)>0) i++;
    i/=5;
    printf("%d\n", i);


    fseek(input,0,SEEK_SET);


    int j;
    char string[20];
    for (j=0;j<i;j++){
    fscanf(input,"%s",string);
    fscanf(input,"ID:%d",&person[j].id);
    fscanf(input,"Name:%s",person[j].name);
    fscanf(input,"Weight:%f",&person[j].weight);
    fscanf(input,"%s",string);
    }

    fclose(input);


//Person:{
  //ID:1214124141
    //Name:Trump
    //Weight:101.50
     //}
    //Person:{
    //ID:5235252525
    //Name:Obama
    //Weight:78.30
    //}

   return 0;
}

您好! 我想从文件中读取结构,但是我的数组 person 在我从文件中读取后才包含0。我的输入文件具有注释行中显示的结构。

我做得不好? 非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

像这样修复

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    long long int id;//32bit int can't hold like 5235252525
    char name[20];//Allocate space
    float weight;
} Person;

#define FORMAT "%*s ID:%lld Name:%19[^\n] Weight:%f %*s"

int main(void){
    FILE *input=fopen("input.txt", "r+");
    if(!input){
        perror("fopen");
        return -1;
    }
    int n = 0;
    Person p;
    while(3==fscanf(input, FORMAT, &p.id, p.name, &p.weight))
        ++n;

    printf("number of record: %d\n", n);
    Person *person = malloc(n * sizeof(Person));
    if(!person){
        perror("malloc");
        fclose(input);
        return -2;
    }

    rewind(input);

    for (int i = 0; i < n; ++i){
        fscanf(input, FORMAT, &person[i].id, person[i].name, &person[i].weight);
    }
    fclose(input);

    //check print
    for (int i = 0; i < n; ++i){
        printf("ID:%lld, Name:%s, Weight:%.2f\n", person[i].id, person[i].name, person[i].weight);
    }
    free(person);

   return 0;
}