• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 696
  • Last Modified:

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");
           exit(1);
      }
 
  /* 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");
   exit(1);
 }
   
  return byteptr;

}

Thanks.
0
Kevin_P23
Asked:
Kevin_P23
1 Solution
 
jkrCommented:
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.
0
 
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.

 
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now