I'm trying to read a file into a buffer in blocks of size BLOCK_SIZE (currently equal to 1000 unsigned chars). My code first finds the number of blocks it will have to read in order to read the entire file (usually 2-4), then iterates through a for loop reading the file (ignore the "+17+filenamesize" stuff, that is all needed for later in the program.
However, only on the first time through, when j=1, does it actually put data into the buf array. In other cases, when j != 1, strlen(buf) returns 0.
I think it is either a problem with how I'm using fseek() to seek to the second part of a file before reading it, or perhaps a memory allocation issue.
Any help would be appreciated for getting it to read the 1000-1999th chars of the file into the buf array.
Attached is the relevant part of the code:
unsigned char *buf;
source = fopen(localpath,"r");
temp = filesize / BLOCK_SIZE + 1;
for (j=1; j <= temp; j++) {
if (j == 1) {
buf = (unsigned char *) malloc((sizeof(unsigned char)) * (BLOCK_SIZE + 17 + filenamesize));
fread(buf+17+filenamesize, sizeof(unsigned char), BLOCK_SIZE, source);
} else if (j == temp) {
buf = (unsigned char *) malloc((sizeof(unsigned char)) * (filesize + 5 - BLOCK_SIZE*(j-1)));
fseek(source, BLOCK_SIZE*(j-1), SEEK_SET); // off by one warning
fread(buf+5, sizeof(unsigned char), filesize - BLOCK_SIZE*(j-1), source);
} else {
buf = (unsigned char *) malloc((sizeof(unsigned char)) * (5+BLOCK_SIZE*(j-1)));
fseek(source, BLOCK_SIZE*(j-1), SEEK_SET); // off by one warning
fread(buf+5, sizeof(unsigned char), BLOCK_SIZE, source);
}
// do stuff with buf here
buf = "";
free(buf);
}