I'm making an archive program in C - I've got it traversing and writing the file contents to a single file, but I can't seem to get the fileHeader structure I've created (using fwrite()) to write into the file (only using two attributes for testing at the moment, I know more will be required). Here's my code:
struct fileHeader {
char name[50];
char path[50];
};
void addToArch(char *inPath, char *archPath, struct fileHeader header) {
FILE *in, *arch;
int ch;
arch = fopen(archPath, "ab");
struct stat sb;
stat(inPath, &sb);
if(S_ISREG(sb.st_mode) == 0) {
fprintf(arch, "\n%s\n", inPath);
printf("Directory detected - skipped");
}
else {
in = fopen(inPath, "rb");
ch = fgetc(in);
fwrite(&header, 1, sizeof(struct fileHeader), in);
while (ch != EOF) {
fputc(ch, arch);
ch = fgetc(in);
}
fclose(in);
fclose(arch);
printf("File copied successfully!\n");
}
}
My calling code is here:
//Create new file header
struct fileHeader header;
//Populate struct fields
snprintf(header.name, 50, "%s", entry->d_name);
snprintf(header.path, 50, "%s", buffer);
addToArch(buffer, "out.txt", header);
I've printed entry->d_name and buffer and they are definitely the strings I want going into the struct. There are no compiler errors, but no header is showing in my archive file, along with the contents.
inandarch. Name your variables more clearly. You can do both, but for clarity and sanity, don't.