Horwing42
Horwing42

Reputation: 31

Dynamic storage of a binary file in C

Participant *readRankingList(const char *filename, int *length) {
    length = 0;
    int i = 0;
    
    FILE *fp;
    fp = fopen(filename, "rb");
    Participant *list;
    
    if (fp == NULL) {
        fprintf(stderr, "*** open of %s failed ***\n", filename);
        return 0;
    }
    
    length = fread((void *)list, sizeof(Participant), LIST_LEN, fp);
    
    while (fread(list, sizeof(length), 1, fp) > 0) {
        list[i] = list;
        i++; 
    }
   
    free(list);
    fclose(fp);
    *length = i;
    return list;
}

I have a binary file, which I open in this part. Now I want to store it with a dynamic storage.

At the moment I get a

Warning : assignment makes pointer from interfer without a cast

and an

Error: incompatible types when assigning to type Participant from type struct Participant

Upvotes: 3

Views: 81

Answers (1)

chqrlie
chqrlie

Reputation: 144780

You must allocate space for the structures with malloc() or calloc(). Seeking to the end of the file will give the number of entries. Reading the entries can be done in a single call to fread.

#include <errno.h>
#include <stdio.h>
#include <string.h>

Participant *readRankingList(const char *filename, int *length) {
    Participant *list;
    size_t count;
    
    // open the file
    FILE *fp = fopen(filename, "rb");
    if (fp == NULL) {
        fprintf(stderr, "*** open of %s failed: %s ***\n", 
                filename, strerror(errno));
        *length = 0;
        return NULL;
    }

    // get the number of structures
    fseek(fp, 0L, SEEK_END);
    count = ftell(fp) / sizeof(Participant);
    if (count == 0) {
        fclose(fp);
        *length = 0;
        return NULL;
    }

    // allocate memory for the array of Participants
    list = calloc(count, sizeof(*list));
    if (list == NULL) {
        fclose(fp);
        *length = 0;
        return NULL;
    }

    // read the structures, update the length, return the pointer.
    rewind(fp);
    *length = fread(list, sizeof(Participant), count, fp);
    fclose(fp);
    return list;
}

Upvotes: 1

Related Questions