• C

Using fread to store sequence of bytes from file to dynamic array

What I'm trying to do is read bytes from a file (infile) and store them into a dynamic array (so later on I can output each byte in hex, octal, binary). I would appreciate any suggestions regarding my code below and if this approach will help me with the task at hand.
My code for the store funtion:

/* s and e represent the first and last bytes of the file to be stored. byte_n is the total
    number of bytes in the infile */

char * store_in_array(int s, int e, int byte_n) {
  char *byteptr;
  size_t size;
  size = ((size_t)e - (size_t)s);          
       /* allocate an array of length size, where */
            /* each element is 1 byte */

     f (( byteptr = (char*)malloc(1 * size)) == NULL)  
           printf("Storage allocation failed.\n");
  /* set file offset to first byte to be read */
     fseek(infile, start, SEEK_SET);    
   /* read size bytes to array byteptr */
  if ( fread((char*)&byteptr, 1, size, infile) == 0)
   printf("Problem in fread().\n");
  return byteptr;


Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

The only problem I see is

  if ( fread((char*)&byteptr, 1, size, infile) == 0)

That should be

  if ( fread(byteptr, 1, size, infile) == 0)

because otherwise you are passing the address of 'byteptr' itself and not the memory are it points to.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Kevin_P23Author Commented:
I gotcha...
The function works properly now, and I see the reasoning behind what I was doing wrong (the library function prototypes can be confusing sometimes).  

Thanks again.

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.