Thread: Trouble trying to read from a bin. file into an array dynamically

  1. #1
    Registered User
    Join Date
    Aug 2017
    Posts
    2

    Trouble trying to read from a bin. file into an array dynamically

    So I am having trouble reading from a bin file (inside a directory), and storying the contents into an array of structs dynamically. I am getting an error saying "each struct field must be read individually", this is part of the requirements.

    Is there an obvious reason I would be having trouble reading the fields. Should I be trying to read them straight into struct stage3 user or create a new array in memory?


    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    struct stage3
    {
            int bell;
            double cream;
            short int apple;
            int brush;
            unsigned long finger;
            char boy [10];
            short int sight;
            long int ocean;
            unsigned short shovel;
            char water;
    };
    
    
    int main(int argc, char** argv)
    {
            int i;
            size_t size;
            struct stage3 *user;
            FILE *fptr;
    
    
            if (argc < 2) { 
                    fprintf(stderr, "Usage");
                    exit(1);
    }
            if ((fptr = fopen(argv[1], "rb+")) == NULL) {
                    fprintf(stderr, "could not open file: %s\n", argv[1]);
                    exit(1);
    }
                    fseek(fptr, 0, SEEK_END);
                    size = (ftell(fptr));
                    fseek(fptr, 0, SEEK_SET); 
    
    
                    user = malloc(size); 
    
            if (user == NULL) {
                    fprintf(stderr, "memeory exhausted\n");
                    exit(1);
    }
                    i = 0;
            while(1) {
                    fread(&user, sizeof(user), 1, fptr);
                    if (feof(fptr)) {
                    break;
    }
                    fclose(fptr);
                    free(user);
            return 0;
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 12-07-2012, 10:44 PM
  2. Replies: 5
    Last Post: 09-17-2011, 08:53 PM
  3. trouble reading a text file into an array
    By Ciaran in forum C Programming
    Replies: 15
    Last Post: 04-04-2011, 05:14 PM
  4. Replies: 4
    Last Post: 07-16-2009, 05:07 PM
  5. File I/O problem for dynamically allocated struct array
    By veecee in forum C++ Programming
    Replies: 2
    Last Post: 05-05-2006, 09:28 PM

Tags for this Thread