C, reading from file into structure

佐手、 提交于 2019-12-17 07:38:39

问题


I've been struggling with this for days and I can't figure out why it doesn't work.

I'm trying to read numbers from file with numbers written like this:

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

my structure:

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 and temph are used in sorting structure)

and reading from a file:

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++;                  

        }           
    }
}

I can change the way the data looks in a file by changing the function that writes it, but I don't think that's the problem. My guess I'm using malloc in a wrong way.


回答1:


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

The scanf family of functions expect addresses. Change the fscanf line to:

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

Side note, this is a seriously misleading line:

else { while(!feof(reads)) {


来源:https://stackoverflow.com/questions/11280523/c-reading-from-file-into-structure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!