这是我的代码,在其中我从“example.txt”中读取256字节,并将其存储在chunk.payload中。
我希望能够先将我的结构体写入“write.txt”,然后再将我读取的内容写入“write.txt”。我已经成功使用fwrite
将chunk.payload中的所有内容写入文件,但是我无法将整个结构体写入文件。
#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;
};
/*Create A dummy packet */
struct packet chunk;
chunk.block_num = 0;
chunk.block_size = 256;
chunk.crc = 0x101001;
chunk.payload = malloc(MAXSIZE + 1); // allocating memory
chunk.payload[MAXSIZE] = '\0';
//read first 256 lines and store into chunk.payload
int read = fread(chunk.payload, sizeof(char), MAXSIZE, fp);
// Write struct to write.txt
fwrite(&chunk, sizeof(chunk), 1, wr);
// Write whatever has been read so far to write.txt
fwrite(chunk.payload, sizeof(char), read, wr);
getch();
fclose(fp);
fclose(wr);
return 0;
我写的调用方式:
fwrite(&chunk, sizeof(chunk), 1, wr);
实际上,允许我编译代码,但在我读取的256字节被写入文件之前,我的文件中写入了随机符号。
正确的方法是什么?
chunk.crc = 0x101001;
这里的short
大于 2 个字节吗? - BLUEPIXY