C, reading from file into structure

73,279
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)) {
Share:
73,279
ozech
Author by

ozech

Updated on May 06, 2020

Comments

  • ozech
    ozech almost 4 years

    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.

  • ozech
    ozech almost 12 years
    thank you, it helped! Why shouldn't I use else { while(!feof(reads)) {?
  • Alex Vallejo
    Alex Vallejo over 10 years
    @ozech Late answer, but you shouldn't use feof() because it only returns false AFTER you have tried to read past the end of the file. It is possible to read in only a partial struct which is probably not what you want. It is also possible that your loop will execute an extra time. You should instead check to see that the value that fscanf returns is >= sizeof(your_struct). That way you know that you have read in an entire struct.