eddiewastaken
eddiewastaken

Reputation: 832

How do I use fwrite() to write a struct to a file?

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.

Upvotes: 0

Views: 635

Answers (2)

user20504930
user20504930

Reputation: 1

It seems the fwrite() call switched the number of items and size of items fields. I think it should be fwrite(&header, sizeof(struct fileHeader), 1, arch);

Upvotes: -2

hobbs
hobbs

Reputation: 240521

Your fwrite is trying to write to in, not arch. Since you don't check the return value of fwrite, this error (trying to write to a file that's opened for read) is undetected.

Upvotes: 4

Related Questions