Trong tập tin có 3 struct thôi nhưng in ra tới 4 struct lận
#include <iostream>
using namespace std;
#include <fstream>
#define MAX 4
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
struct SanPham
{
int ma;
char ten[30];
int gia;
};
void NhapSanPham(SanPham &a)
{
cout<<"Moi nhap ma: ";
cin>>a.ma;
cout<<"Moi nhap ten: ";
cin.ignore();
gets(a.ten);
cout<<"Gia: ";
cin>>a.gia;
}
void NhapDanhSachSanPham(SanPham dSachSP[],int n)
{
for(int i=0;i<n;i++)
{
cout<<"Moi nhap san pham thu "<<i+1<<endl;
NhapSanPham(dSachSP[i]);
}
}
void XuatSP(SanPham a)
{
cout<<a.ma<<"-"<<a.ten<<"-"<<a.gia<<endl;
}
void XuatDanhSachSanPham(SanPham dSachSP[],int n)
{
for(int i=0;i<n;i++)
{
XuatSP(dSachSP[i]);
}
}
void GhiFile(SanPham dSachSP[],int n)
{
ofstream FileGhi("structSP.dat",ofstream::binary);
for(int i=0;i<n;i++)
{
FileGhi.write((char*)&dSachSP[i],sizeof(SanPham));
}
FileGhi.close();
}
void DocFile(SanPham dSachSP[],int &n)
{
ifstream FileDoc("structSP.dat",ifstream::binary);
int i=0;
while(FileDoc.eof()==0)
{
FileDoc.read((char*)&dSachSP[i++],sizeof(SanPham));
}
FileDoc.close();
n=i;
}
int main(int argc, char** argv) {
/*SanPham dSachSP[MAX];
NhapDanhSachSanPham(dSachSP,3);
cout<<"Danh sach san pham sau khi ban nhap la: \n";
XuatDanhSachSanPham(dSachSP,3);
GhiFile(dSachSP,3);*/
SanPham dSachSP[MAX];
int soSP;
DocFile(dSachSP,soSP);
XuatDanhSachSanPham(dSachSP,soSP);
return 0;
}