如何在文件中保存一个结构体?

zenonline 2003-09-06 10:30:07
源码:
#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型的可以正确显示,而字符数组只是显示乱码。

请各位高手指教,不胜感激!
...全文
192 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
rhs 2003-09-09
  • 打赏
  • 举报
回复
这是C++还是C???
蝎子i软件 2003-09-09
  • 打赏
  • 举报
回复
可能原因://为经过调试的...
fp=fopen("test","w+b");
你用的w打开的文件,
却用
fread(&n,sizeof(model),1,fp);
去读。

解决方法如 yiyi1977(yy) 所言。
蝎子i软件 2003-09-09
  • 打赏
  • 举报
回复
不好意思,
刚仔细看了一下,
思维挺清晰的。
蝎子i软件 2003-09-09
  • 打赏
  • 举报
回复
其实代码挺整齐的,
是思维乱了。
cymlife 2003-09-09
  • 打赏
  • 举报
回复
同意一楼:可以直接读写结构体。
程序写得如烂棉花,没有风格,多加注意。

程序代码是给别人阅读的!!!!
yiyi999999999 2003-09-07
  • 打赏
  • 举报
回复
fwrite后fclose,
然后再fopen,
再fread。
你的程序太乱了,根本不用那么复杂。

69,382

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧