diff --git a/src/tar.c b/src/tar.c index e8e74a7..14a519f 100644 --- a/src/tar.c +++ b/src/tar.c @@ -6,6 +6,7 @@ int minitar_read_header(struct minitar* mp, struct tar_header* hdr); int minitar_validate_header(struct tar_header* hdr); void minitar_parse_tar_header(struct tar_header* hdr, struct minitar_entry_metadata* metadata); struct minitar_entry* minitar_dup_entry(struct minitar_entry* original); +char* minitar_read_file(struct minitar_entry_metadata* metadata, struct minitar* mp); struct minitar* minitar_open(const char* path) { @@ -41,7 +42,9 @@ static struct minitar_entry* minitar_attempt_read_entry(struct minitar* mp, int* } *valid = 1; minitar_parse_tar_header(&hdr, &entry.metadata); - // FIXME: Actually read the file and place it in buf. + char* buf = minitar_read_file(&entry.metadata, mp); + if(!buf) return NULL; + entry.ptr = buf; return minitar_dup_entry(&entry); } @@ -57,5 +60,6 @@ struct minitar_entry* minitar_read_entry(struct minitar* mp) void minitar_free_entry(struct minitar_entry* entry) { - free(entry); // FIXME: Also free the file's content, when it's placed in buf. + free(entry->ptr); + free(entry); } \ No newline at end of file diff --git a/src/tar.h b/src/tar.h index a5ff046..e83652c 100644 --- a/src/tar.h +++ b/src/tar.h @@ -18,7 +18,7 @@ struct tar_header { char devmajor[8]; char devminor[8]; char prefix[155]; - char padding[12]; + char padding[12]; // to make the structure 512 bytes } __attribute__((packed)); #endif \ No newline at end of file diff --git a/src/util.c b/src/util.c index 627603d..a6291a1 100644 --- a/src/util.c +++ b/src/util.c @@ -87,4 +87,26 @@ struct minitar_entry* minitar_dup_entry(struct minitar_entry* original) if(!new) return NULL; memcpy(new, original, sizeof *new); return new; +} + +char* minitar_read_file(struct minitar_entry_metadata* metadata, struct minitar* mp) +{ + char* buf = malloc(metadata->size + 1); + if(!buf) return NULL; + + size_t nread = fread(buf, 1, metadata->size, mp->stream); + if(!nread) + { + free(buf); + if(feof(mp->stream)) return NULL; + if(ferror(mp->stream)) minitar_panic("Error while reading file data from tar archive"); + __builtin_unreachable(); + } + + long rem = 512 - (nread % 512); + fseek(mp->stream, rem, SEEK_CUR); // move the file offset over to the start of the next block + + buf[nread] = 0; + + return buf; } \ No newline at end of file