C,从文件读入的结构C,从文件读入的结构(C, reading from file into str

2019-06-14 10:29发布

我一直在挣扎与此几天,我想不通为什么它不工作。

我想用这样写的号码从文件中读取数据:

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,温度和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以错误的方式。

Answer 1:

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)) { 


文章来源: C, reading from file into structure
标签: c file structure