This is my code where I read 256 bytes in "example.txt" and saved it in chunk.payload.
I want to write my structure first in "write.txt" and then write the content that I read, "write.txt". I was able to use fwriteto write the entire chunk.payload file to a file, but it is difficult for me to write the entire structure to a file.
#define MAXSIZE 256
int main(void){
FILE *fp = fopen("C:\\Users\\alice\\Desktop\\example.txt", "r");
FILE *wr = fopen("C:\\Users\\alice\\Desktop\\write.txt", "w+");
struct packet{
unsigned short block_num;
unsigned short block_size;
unsigned short crc;
unsigned char *payload;
};
struct packet chunk;
chunk.block_num = 0;
chunk.block_size = 256;
chunk.crc = 0x101001;
chunk.payload = malloc(MAXSIZE + 1);
chunk.payload[MAXSIZE] = '\0';
int read = fread(chunk.payload, sizeof(char), MAXSIZE, fp);
fwrite(&chunk, sizeof(chunk), 1, wr);
fwrite(chunk.payload, sizeof(char), read, wr);
getch();
fclose(fp);
fclose(wr);
return 0;
How I wrote my call:
fwrite(&chunk, sizeof(chunk), 1, wr);
actually allowed me to compile the code, but in the end I had random characters written to a file before the 256 bytes I read were written to my file
What is the correct method for doing this?
source
share