问题描述
我正在开发一个必须用标准C编码的项目。(不是C ++。)前一段时间,我编写了以下程序,将不同结构的内容写入二进制文件:
#include <stdio.h>
#include <stdlib.h>
typedef struct structA{
int a,b,c;
}AAA;
typedef struct structB{
int a,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,fd);
fwrite((char*)&b1,sizeof(BBB),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,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);”错误,修复了第一个程序因为剪切粘贴错误。
解决方法
正如已经指出的,您正在将指针a1
的地址传递给memcpy,与a2
和b1
相同。应该是
memcpy ( BlockOfMemory,a1,sizeof( AAA ) );
memcpy ( (BlockOfMemory+sizeof(AAA)),a2,sizeof( AAA ) );
memcpy ( (BlockOfMemory+sizeof(AAA)+sizeof(AAA)),b1,sizeof( BBB ) );
如果要打印BlockOfMemory
的内容,则需要回退到AAA*
和BBB*
并使用指针算术移动,就像这样
unsigned char* tmp = BlockOfMemory;
AAA* x = (AAA*)tmp;
printf("==> %d %d %d\n",x->a,x->b,x->c);
tmp += sizeof(AAA);
x = (AAA*)tmp;
printf("==> %d %d %d\n",x->c);
tmp += sizeof(AAA);
BBB* y = (BBB*)tmp;
printf("==> %d %d %d %d %d\n",y->a,y->b,y->c,y->d,y->e);