1. 程式人生 > >C++對類的二進位制檔案儲存與顯示

C++對類的二進位制檔案儲存與顯示

在C++中有相關序列化和反序列化函式,這裡不用C++提供的序列化和反序列化函式。
#include<iostream>
#include<fstream>
#include<string.h>
using namespace std;
class Item{
	char partCode[5];
	char descrip[20];
	int num;
	float price ;
public:
	static int count;
	Item(){partCode[0]='\0';}
	Item(char P[],char D[],int N,float PR):num(N),price(PR){
		strcpy(partCode,P);
		strcpy(descrip,D);
	}
	void show();
};
int Item::count=1;
void Item::show(){
	cout<<count++<<endl;
	cout<<partCode<<endl;
	cout<<descrip<<endl;
	cout<<num<<endl;	
	cout<<price<<endl;
}
class Inventory{
	Item parts[50];
public:
	static int numInInv;
	Inventory(){}
	void addToInv(char [],char [],int ,float);
	void toDisk(void);
};
void Inventory::addToInv(char P[],char D[],int N,float PR){
	parts[numInInv]=Item(P,D,N,PR);
	numInInv++;
}
void Inventory::toDisk(void){
	ofstream invOut("inv.dat");
	invOut.write((char *)this,sizeof(*this));
	invOut.close();
}
int Inventory::numInInv=0;
int main()
{

	Inventory parts;
	parts.addToInv("aaaa","aabbb",14,2.34);
	parts.addToInv("bbbb","bbccc",24,3.34);
	parts.addToInv("cccc","ccbbb",4,3.4);
	parts.addToInv("aaaa","aabbb",14,2.34);
	parts.toDisk();
	cout<<Inventory::numInInv<<"parts were wirteen."<<endl;
	Item item[50];
	int i=4;
	int j=0;
	ifstream fin;
	fin.open("inv.dat");
	while(i){
		fin.read((char *)&item[j],sizeof(item[j]));
		item[j].show();
		i--;
		j++;
	}
	
	return 0;
}
也可一次性讀入
#include<iostream>
#include<fstream>
#include<string.h>
using namespace std;
class Item{
	char partCode[5];
	char descrip[20];
	int num;
	float price ;
public:
	static int count;
	Item(){partCode[0]='\0';}
	Item(char P[],char D[],int N,float PR):num(N),price(PR){
		strcpy(partCode,P);
		strcpy(descrip,D);
	}
	void show();
};
int Item::count=1;
void Item::show(){
	cout<<count++<<endl;
	cout<<partCode<<endl;
	cout<<descrip<<endl;
	cout<<num<<endl;	
	cout<<price<<endl;
}
class Inventory{
	Item parts[50];
public:
	static int numInInv;
	Inventory(){}
	void addToInv(char [],char [],int ,float);
	void toDisk(void);
};
void Inventory::addToInv(char P[],char D[],int N,float PR){
	parts[numInInv]=Item(P,D,N,PR);
	numInInv++;
}
void Inventory::toDisk(void){
	ofstream invOut("inv.dat");
	invOut.write((char *)this,sizeof(*this));
	invOut.close();
}
int Inventory::numInInv=0;
int main()
{

	Inventory parts;
	parts.addToInv("aaaa","aabbb",14,2.34);
	parts.addToInv("bbbb","bbccc",24,3.34);
	parts.addToInv("cccc","ccbbb",4,3.4);
	parts.addToInv("aaaa","aabbb",14,2.34);
	parts.toDisk();
	cout<<Inventory::numInInv<<"parts were wirteen."<<endl;
	Item item[4];
	int i=0;
	int j=0;
	ifstream fin;
	fin.open("inv.dat");
//	while(i){
	fin.read((char *)&item[0],sizeof(item));
//		item[j].show();
//		i--;
//		j++;
//		cout<<sizeof(item[j])<<endl;
//	}
	while(i<4){
		item[i++].show();
	}
	return 0;
}