C、从文件读入结构体

2024-02-13

我已经为此苦苦挣扎了好几天,但我不明白为什么它不起作用。

我正在尝试从文件中读取数字,数字如下所示:

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以错误的方式。


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

The scanf函数族需要地址。改变fscanf线路至:

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

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

else { while(!feof(reads)) {
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C、从文件读入结构体 的相关文章

随机推荐