C++中结构体数据的文件读写

结构体中数据有很多类型。
class Goods
{
protected:
	char goods_name[50]; //商品名称
	int goods_number; //商品代码
	char person_name[30]; //经办人
	int price; //进货价
	int amount; //库存量
	Goods *next;//定义指向类Goods的指针变量next
public:
	Goods(int goods_number=0,char*goods_name="null",char*person_name="null",int price=0,int amount=0)//定义构造函数
	{
		this->goods_number=goods_number;
		strcpy(this->goods_name,goods_name);
		strcpy(this->person_name,person_name);
		this->price=price;
		this->amount=amount;
	}
	void ShowData()//定义输出函数
	{
		cout<<"goods_number:"<<goods_number<<" goods_name:"<<goods_name<<" person_name:"<<person_name<<" price:"<<price<<" amount:"<<amount<<endl;
	}
};

不建议使用一般的存储方式,而应该采取二进制读写,这样会方便读写操作,尤其是读取操作。

二进制从内存写进文件:

#include <iostream.h>  
#include <fstream.h>  
#include <stdlib.h>
#include <cstring>
class Goods
{
protected:
	char goods_name[50]; //商品名称
	int goods_number; //商品代码
	char person_name[30]; //经办人
	int price; //进货价
	int amount; //库存量
	Goods *next;//定义指向类Goods的指针变量next
public:
	Goods(int goods_number=0,char*goods_name="null",char*person_name="null",int price=0,int amount=0)//定义构造函数
	{
		this->goods_number=goods_number;
		strcpy(this->goods_name,goods_name);
		strcpy(this->person_name,person_name);
		this->price=price;
		this->amount=amount;
	}
	void ShowData()//定义输出函数
	{
		cout<<"goods_number:"<<goods_number<<" goods_name:"<<goods_name<<" person_name:"<<person_name<<" price:"<<price<<" amount:"<<amount<<endl;
	}
};
int main () 
{
    ofstream out("data.txt",ios::app|ios::binary);
	Goods x(1,"name1","das",1,1);
	Goods y(2,"name2","das2",2,2);
	Goods z(3,"name3","das3",3,3);
    if (out.is_open()) 
    {
		out.write((char*)&x,sizeof(x));
		out.write((char*)&y,sizeof(y));
		out.write((char*)&z,sizeof(z));
    }
    return 0;
}

二进制从文件读取到内存

#include <iostream.h>  
#include <fstream.h>  
#include <stdlib.h>
#include <cstring>
class Goods
{
protected:
	char goods_name[50]; //商品名称
	int goods_number; //商品代码
	char person_name[30]; //经办人
	int price; //进货价
	int amount; //库存量
	Goods *next;//定义指向类Goods的指针变量next
public:
	Goods(int goods_number=0,char*goods_name="null",char*person_name="null",int price=0,int amount=0)//定义构造函数
	{
		this->goods_number=goods_number;
		strcpy(this->goods_name,goods_name);
		strcpy(this->person_name,person_name);
		this->price=price;
		this->amount=amount;
	}
	void ShowData()//定义输出函数
	{
		cout<<"goods_number:"<<goods_number<<" goods_name:"<<goods_name<<" person_name:"<<person_name<<" price:"<<price<<" amount:"<<amount<<endl;
	}
};
int main () 
{  
   Goods x,y,z;
   ifstream in("data.txt",ios::binary);  
   if (! in.is_open())  
   { 
	   cout << "Error opening file";
	   exit (1); 
   }
   while (!in.eof() )
   {  
       in.read((char*)&x,sizeof(x));
	   in.read((char*)&y,sizeof(y));
	   in.read((char*)&z,sizeof(z));
   }
   x.ShowData();
   y.ShowData();
   z.ShowData();
   return 0;  
}
注意下,二进制存储的文件data.txt,打开后是乱码的,只作为存储功能使用,但是VC是能自己识别的,也可以使用其他可查看二进制的文件工具查看。
编译环境:VC++6.0
用途:课程设计

你可能感兴趣的:(C++中结构体数据的文件读写)