#include "stdafx.h"
using namespace std;
class CPeople
{
public:
CPeople(void);
~CPeople(void);
void change(int,string,bool,string,int,float);
void insert(string,bool,string,int,float);
void display(int);
void found(string);
void iconnect(void);
void iclose(void);
void oconnect(int);
void oclose(void);
private:
string dbfile;
string dbfilebk;
ifstream in;
ofstream out;
string name;
bool sex;
string address;
int grade;
float score;
};
CPeople::CPeople(void){dbfile="db.txt";dbfilebk="db_bk.txt";}
CPeople::~CPeople(void)
{
if(in.is_open()) in.close();
if(out.is_open()) out.close();
}
void CPeople::iconnect(void)
{
using std::ios;
in.open(dbfile.c_str());
if(in.fail())
{
cout<<"An error occured when programe opening the dbfile!"<
}
}
void CPeople::iclose(void)
{
in.close();
}
void CPeople::oconnect(int _num)
{
using std::ios;
if(_num!=-1)
out.open(dbfile.c_str(),ios::app);
else
out.open(dbfilebk.c_str(),ios::app);
if(out.fail())
{
cout<<"An error occured when programe opening the dbfile!"<
}
}
void CPeople::oclose(void)
{
out.close();
}
void CPeople::insert(string _name,bool _sex,string _address,int _grade,float _score)
{
oconnect(0);
out<<_name.c_str()<<","<<_sex<<","<<_address.c_str()<<","<<_grade<<","<<_score<<"\n";
oclose();
cout<<"Inserting Finished!"<
void CPeople::change(int _idx,string _name,bool _sex,string _address,int _grade,float _score)
{
iconnect();
oconnect(-1);
int cnt = 1;
string tmp;
in>>tmp;
while(!in.eof())
{
if(cnt==_idx)
out<<_name.c_str()<<","<<_sex<<","<<_address.c_str()<<","<<_grade<<","<<_score<<"\n";
else
out<
in>>tmp;
cnt++;
}
oclose();
iclose();
//移除原来文件
remove(dbfile.c_str());
rename(dbfilebk.c_str(),dbfile.c_str());
cout<<"Editing Finished!"<
void CPeople::display(int _idx)//from 0 to unlimit
{
iconnect();
if(_idx<0)//显示全部
{
string tmp;
in>>tmp;
while(!in.eof())
{
cout<
}
}
else
{
int cnt = 1;
string tmp;
in>>tmp;
while(!in.eof())
{
if(cnt==_idx)
{
cout<
}
in>>tmp;
cnt++;
}
}
iclose();
}
void CPeople::found(string _name)
{
iconnect();
string tmp;
in>>tmp;
while(!in.eof())
{
if(_name==tmp.substr(0,tmp.find(",")))
{
cout<
in>>tmp;
}
iclose();
}
int _tmain(int argc, _TCHAR* argv[])
{
CPeople p;
p.insert("DD",0,"sh",1,100);
//p.found("cc");
//p.change(7,"DD",0,"sh",1,100);
// p.display(-1);//显示全部
//p.display(3);
return 0;
}
_________________________
stdafx.cpp
_________________________
#include "stdafx.h"
_________________________
stdafx.h
_________________________
#pragma once
#include
#include
#include
#include
-------------------------------------------------
在程序相同目录下新建一个名字为db.txt的空文本文件
-------------------------------------------------
PS:在VS.Net2003 Windows XP Pro下测试运行过