现在的位置: 首页 > 综合 > 正文

内存数据保存到文件

2013年12月07日 ⁄ 综合 ⁄ 共 524字 ⁄ 字号 评论关闭

#include <stdio.h>
#include <string.h>
int main( void )
{
 FILE *stream;
 typedef struct _tt{
  int a;
  int b;
  char buf[20];
 }tt;//定义结构体
 tt temp;
 temp.a=10;
 temp.b=20;
 strcpy(temp.buf,"hello");//为结构体赋值
 
 int c=sizeof(temp);
 stream= fopen("at.dat","w+");//打开文件
 fwrite(&temp,sizeof(temp),1,stream);//将结构体的内容写入到文件中
 
 char *pbuf=new char[sizeof(temp)];//在内存中开辟一块temp大小的区域
 
 fseek(stream,0,SEEK_SET);//从“at.dat”将文件的读写指针移动到文件开始处
 fread(pbuf,sizeof(temp),1,stream);//从文件中读取一个结构体到pbuf处
    fclose(stream);
    tt *p=(tt*)pbuf;
 printf("%d %d %s",p->a,p->b,p->buf);
}

抱歉!评论已关闭.