Kevin_P23
asked on
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.
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.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
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.