I want to write a simple version of tar, that is able to archive files provided as command line arguments (no compression needed). I've just started learning about binary files so I'm a bit lost.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
char name[100];
char mode[8];
char uid[8];
char ouid[8];
char size[12];
char time[12];
char checksum[8];
char type[1];
char linkname[100];
}HEADER;
void readHeader(FILE *input)
{
HEADER file;
fread(&file, sizeof(file), 1, input);
//here I think I should use fwrite to write the header to the tar file
}
int main(int argc, char **argv)
{
FILE *fin = fopen("tarOutput.tar", "wb");
if(!fin)
{
fprintf(stderr, "Error opening the .tar output file.\n");
exit(-1);
}
if(argc < 3)
{
fprintf(stderr, "Invalid format.\nCorrect format: ./a.out c tarOutput.tar file1 file2 ...\n");
exit(1);
}
if(strcmp(argv[1], "c") != 0)
{
fprintf(stderr, "Invalid option. You should use 'c' as the second argument.\nCorrect format: ./a.out c tarOutput.tar file1 file2 ...\n");
exit(2);
}
for(int i = 3; i <= argc; i++) // do this for each file specified as argument; start at 3 because argv[0,1,2] are program name, c, tar output file
{
//int fileIndex = 1;
FILE *fileInput = fopen(argv[i], "rb");
if(!fileInput)
{
fprintf(stderr, "Failed to open file '%s' for reading\n", argv[i]);
exit(-2);
}
readHeader(fileInput);
}
fclose(fin);
return 0;
}
I'm using the following wiki page as model for the header tar (computing) - Wikipedia . The header is 512 bytes. So I know I should first write the header followed by the contents of each file. Could you show me some steps how to correctly implement the header? Thank you!