我正在尝试将结构指针写入文件。我想要写的是一个指向字符缓冲区的结构指针,然后从缓冲区中检索指针,最后将整个结构写入文件。使用fwrite将结构指针写入文件
而不是写整个结构,我得到文件中的垃圾数据。
我在代码中丢失了什么或者犯了一些错误。
完全粘贴我的测试代码。
#include <stdio.h>
# include<stdlib.h>
#include <string.h>
typedef struct dummy_s {
int a;
} dummy_t;
void main(int argc, char* argv)
{
char *s1;
s1 = malloc(sizeof(dummy_t)*1000);
dummy_t * tmp1;
tmp1 = (dummy_t *)s1;
tmp1 -> a = 100;
FILE *f;
f = fopen("dummyfile.txt","w");
dummy_t * tmp = NULL;
tmp = malloc(sizeof(dummy_t));
memcpy(tmp, s1, sizeof(dummy_t));
fwrite(tmp,sizeof(struct dummy_s),1,f);
fclose(f);
}
[编者对于编译错误 - 对不起] 干杯! Naren
那么fwrite()调用甚至编译...? (我没有C编译器) – 2011-02-25 13:44:28
什么是一堆疯狂的操作...... – pmod 2011-02-25 13:45:23
什么是memcpy中的“d”(tmp,d,sizeof(dummy_t));? – pmod 2011-02-25 13:48:00