这是我的代码,我在“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 个字节写入我的文件之前,我最终将随机符号写入我的文件
执行此操作的正确方法是什么?
最佳答案
您的第一个 fwrite 尝试将数据包结构的二进制内容写入您的 write.txt 文件:
// 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);
正在写入您的 malloc 负载的内容。我不认为你想将二进制文件写入文件。如果你想在有效负载之前将数据包结构值作为文本写入文件,你将必须像 fprintf 一样将它们一个一个地执行,例如
// write contents of 'chunk' to text file
fprintf( wr, "block_num= %d\n", chunk.block_num );
...
fwrite(chunk.payload, sizeof(char), read, wr);
另请注意,如果读取小于 MAXSIZE,您的负载文本将不会正确地以零终止。
关于c - 用c将结构写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21654643/