如何在文件中保存一个结构体?
源码:
#include "string.h"
#include <iostream.h>
#include <stdio.h>
#include "stdafx.h"
class model
{
public:
int i;
int j;
char s[4];
};
int main(int argc, char* argv[])
{
char *p,*q;
model *ptr,m,n;
FILE *fp;
int i;
i=321;
m.i=123;
m.j=456;
p=m.s;
p="des";
m.s[0]='a';
m.s[1]='b';
m.s[2]='c';
m.s[3]='\0';
strcpy(p,"des");
printf("\n\t%s\n",m.s);
printf("\n\t%s\n",p);
fp=fopen("test","w+b");
printf("\n\t%i\n",sizeof(model));
fwrite(&m,sizeof(model),1,fp);
rewind(fp);
q=n.s;
q="ppp";
ptr=&n;
q=ptr->s;
printf("\n\t%s\n",n.s);
printf("\n\t%s\n",q);
fread(&n,sizeof(model),1,fp);
fclose(fp);
printf("\n\t%i\n",m.i);
printf("\n\t%i\n",m.j);
printf("\n\t%i\n",i);
printf("\n\t%s\n",n.s);
q=n.s;
printf("\n\t%s\n",q);
return 0;
}
我的意图是在自定义的结构体中保留一个字符数组,保存在文件里;然后再读出来,并显示保存在其中的字符数组。
但是,运行的结果是int型的可以正确显示,而字符数组只是显示乱码。
请各位高手指教,不胜感激!