#include <iostream>
using namespace std;
struct Person
{
int iAge;
char szName[20];
Person(int iAge,string strName)
{
this->iAge = iAge;
strcpy(szName,strName.c_str());
}
};
class BookFile
{
private:
FILE* pFile;
int iLen;
int iPersonSize;
public:
BookFile()
{
iPersonSize = sizeof(Person);
}
bool Open(const char* szName,bool bEdit = false);
bool Read(Person* pPerson,int index);
bool Write(Person* pPerson,int index);
void Close();
};
bool BookFile::Read(Person* pPerson,int index)
{
if(index>=iLen)
{
return false;
}
fseek(pFile,index*iPersonSize,SEEK_SET);
fread(pPerson,iPersonSize,1,pFile);
return true;
}
bool BookFile::Write(Person* pPerson,int index)
{
fseek(pFile,index*iPersonSize,SEEK_SET);
fwrite(pPerson,iPersonSize,1,pFile);
return true;
}
bool BookFile::Open(const char* szName,bool bEdit /* = false */)
{
pFile = fopen(szName,bEdit?"r+b":"rb");
if(NULL==pFile)
{
return false;
}
fseek(pFile,0,SEEK_END);
iLen = ftell(pFile)/iPersonSize;
return true;
}
void BookFile::Close()
{
fclose(pFile);
}
C++ 把对象写入到文件中并按位置读取
最新推荐文章于 2022-12-22 21:13:16 发布