Read file contents and store them in entry->ptr

This commit is contained in:
apio 2022-11-06 10:33:37 +01:00
parent 0952af15b4
commit baf8318c29
3 changed files with 29 additions and 3 deletions

View File

@ -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);
}

View File

@ -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

View File

@ -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;
}