diff --git a/main.c b/main.c index 861da81..ca46d18 100644 --- a/main.c +++ b/main.c @@ -4,28 +4,47 @@ #include #include +bool writedata(const char *basename, + unsigned int id, + const char *data, + unsigned int dsize) { + bool status = false; + char *fn = (char*)malloc(sizeof(char) * strlen(basename) + 4); + sprintf(fn, "%s_%d", basename, id); + FILE *out = fopen(fn, "w"); + if (out != NULL) { + fwrite(data, sizeof(char), dsize, out); + fclose(out); + status = true; + } + free(fn); + return status; +} + void unpackpld(const char *buffer, const struct PldHeader *ph, - const char *name) { + const char *name, + unsigned int s) { char *wbuffer = NULL; // write buffer that will change. unsigned int wsize = 0; // size of wbuffer. unsigned int i; - for (i = 0; (i + 1) < (ph -> numOffset); i++) { + unsigned int start = 0; // ending offset for data + unsigned int end = 0; // ending offset for data + for (i = 0; (i + 1) < (ph -> numOffset) + 1; i++) { printf("start: %x - end: %x\n", ph -> offsets[i], ph -> offsets[i + 1]); + start = ph -> offsets[i]; + // the last offset still has some data until the end of file + end = (i == (ph -> numOffset) - 1) ? s : ph -> offsets[i + 1]; // copy sector to write buffer - wsize = (ph -> offsets[i + 1]) - (ph -> offsets[i]) + 1; + wsize = end - start; + printf("end is %x - i is %d - wsize is %x\n", end, i, wsize); wbuffer = (char*)malloc(sizeof(char) * wsize); - memcpy(wbuffer, buffer + (ph -> offsets[i]), wsize); + memcpy(wbuffer, buffer + start, wsize); // create a file. - char *fn = (char*)malloc(sizeof(char)*strlen(name) + 4); - sprintf(fn, "%s_%d", name, i); - FILE *out = fopen(fn, "w"); - fputs(wbuffer, out); - fclose(out); - free(fn); + writedata(name, i, wbuffer, wsize); } free(wbuffer); } @@ -60,7 +79,7 @@ struct PldHeader *read_pldheader(const char *buffer) { return ph; } -char *readpld(const char *fname) { +char *readpld(const char *fname, unsigned int *s) { FILE *f = fopen(fname, "rb"); unsigned int size = 0; // number of elements to buffer; unsigned int rcnt = 0; // number of char's read by fread(...) @@ -85,15 +104,18 @@ char *readpld(const char *fname) { return NULL; } fclose(f); + *s = rcnt; return buf; } int main(int argc, char ** argv) { - char *filename = argv[1]; - char *filedata = readpld(filename); - if (filedata != NULL) { + char *filename = argv[1]; + unsigned int fsize = 0; + char *filedata = readpld(filename, &fsize); + printf("fsize is %i\n", fsize); + if (filedata != NULL && fsize != 0) { struct PldHeader *pldh = read_pldheader(filedata); - unpackpld(filedata, pldh, filename); + unpackpld(filedata, pldh, filename, fsize); free(pldh -> offsets); free(pldh); }