C,从文件读入结构

时间:2012-07-01 08:21:12

标签: c file structure

我一直在努力解决这个问题,我无法弄清楚为什么它不起作用。

我正在尝试从文件中读取带有这样的数字的数字:

0 2012 1 1 2000.000000
0 2012 1 1 3000.000000
1 2012 1 1 4500.000000

我的结构:

struct element{

        int id;
        int sign;
        int year;
        int month;
        double amount;

        struct element *next;


};

struct queue{
    struct element *head;
    struct element *tail;
    struct element *head2; 
    struct element *temp;  
    struct element *temph; 

    int size;
};
  

(head2,temp和temph用于排序结构)

并从文件中读取:

void read_str(struct queue *queue){

    FILE *reads;

    char filename[40];
    int temp;

    printf("Type in name of the file\n");
    scanf("%s",&filename);
    reads=fopen(filename, "r");
    if (reads==NULL) {
        perror("Error");
        return 1;
    }
    else { 
        while(!feof(reads)) {
            struct element *n= (struct element*)malloc(sizeof(struct element));             
            fscanf(reads,"%d %d %d %d %lf", n->id, n->sign, n->year, n->month, n->amount);                  
            n->next=NULL;                   

            if(queue->head ==NULL) {
                queue->head=n;
            }
            else {
                queue->tail->next=n;
            }

            queue->tail=n;
            queue->size++;                  

        }           
    }
}

我可以通过更改写入它的函数来更改数据在文件中的显示方式,但我不认为这是问题所在。我的猜测是我以错误的方式使用malloc

1 个答案:

答案 0 :(得分:20)

fscanf(reads,"%d %d %d %d %lf", n->id, n->sign, n->year, n->month, n->amount);

scanf系列函数需要地址。将fscanf行更改为:

fscanf(reads,"%d %d %d %d %lf", &n->id, &n->sign, &n->year,
    &n->month, &n->amount);

旁注,这是一个严重误导的行:

else { while(!feof(reads)) {