【发布时间】:2020-08-24 15:15:49
【问题描述】:
我正在做一个必须用标准 C 编码的项目。(不是 C++。)前段时间,我编写了以下程序,将不同结构的内容写入二进制文件:
#include <stdio.h>
#include <stdlib.h>
typedef struct structA{
int a, b, c;
}AAA;
typedef struct structB{
int a, b, c, d, e;
}BBB;
int main( int argc, char **argv ){
// Create and open the output file
FILE *fd = fopen("test.txt", "w");
AAA* a1 = (AAA*)malloc( sizeof(AAA) );
AAA* a2 = (AAA*)malloc( sizeof(AAA) );
BBB* b1 = (BBB*)malloc( sizeof(BBB) );
a1->a = 1; a1->b = 2; a1->c = 3;
a2->a = 4; a2->b = 5; a2->c = 6;
b1->a = 10; b1->b = 20; b1->c = 30; b1->d = 40; b1->e = 50;
// Write all these structs to the file:
fwrite((char*)&a1, sizeof(AAA), 1, fd);
fwrite((char*)&a2, sizeof(AAA), 1, fd);
fwrite((char*)&b1, sizeof(BBB), 1, fd);
// Close the file
fclose( fd );
free( a1 );
free( a2 );
free( b1 );
printf("END OF PROGRAM.\n");
return 0;
}
上面的工作完美......即使我无法通过查看输出来判断:
me@ubuntu:/home/me# more test.txt
▒$▒&V
me@ubuntu:/home/me#
我有另一个程序可以读取这个文件并从结构中提取所有信息。所以我知道上面的代码正是我想要的。
但现在,我需要将这些结构写入一块分配的内存,而不是写入文件。我认为这很容易:
#include <stdio.h>
#include <stdlib.h>
typedef struct structA{
int a, b, c;
}AAA;
typedef struct structB{
int a, b, c, d, e;
}BBB;
int main( int argc, char **argv ){
u_char* BlockOfMemory = (u_char*) malloc( sizeof(u_char) * 100 );
AAA* a1 = (AAA*)malloc( sizeof(AAA) );
AAA* a2 = (AAA*)malloc( sizeof(AAA) );
BBB* b1 = (BBB*)malloc( sizeof(BBB) );
a1->a = 1; a1->b = 2; a1->c = 3;
a2->a = 4; a2->b = 5; a2->c = 6;
b1->a = 10; b1->b = 20; b1->c = 30; b1->d = 40; b1->e = 50;
// Write all these structs into BlockOfMemory:
memcpy ( BlockOfMemory, &a1, sizeof( AAA ) );
memcpy ( (BlockOfMemory+sizeof(AAA)), &a2, sizeof( AAA ) );
memcpy ( (BlockOfMemory+sizeof(AAA)+sizeof(AAA)), &b1, sizeof( BBB ) );
printf("==> %hhn\n", BlockOfMemory);
free( a1 );
free( a2 );
free( b1 );
free( BlockOfMemory );
printf("END OF PROGRAM.\n");
return 0;
}
成功了吗?我不知道:
me@ubuntu:/home/me# gcc -Wall writeBlock.c
me@ubuntu:/home/me# ./a.out
==>
END OF PROGRAM.
me@ubuntu:/home/me#
这里的目标是内存块必须包含与二进制文件完全相同的信息。我的代码编译和运行的情况很奇怪,但是鉴于我拥有的工具(VI 和 GCC),我无法验证我的代码是否正确或偏离标准。
谁能给点建议?另外,memcpy() 会是这里使用的函数吗?谢谢。
编辑:当我错误地添加了第二个“free(b1);”时,修复了第一个程序因为剪切-粘贴错误。
【问题讨论】:
-
您正在通过
memcpy和&a1等传递ptr-to-ptr。 -
如果您在
printf中使用%hhn,您将无法查看任何内容。n说明符用于将到目前为止写入的字符数写入变量,它不会打印任何内容。 -
在第二个示例中,
%hhn根本没有任何意义。%n格式将迄今为止打印的字符数写入参数指向的位置。 -
哦,你是对的。
标签: c heap-memory memcpy