內存數據保存到文件

#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);
}
相關文章
相關標籤/搜索