首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

C++中关于读取文件的疑惑。该怎么处理

2012-03-04 
C++中关于读取文件的疑惑。。。定义一个类classPerson//基本资料{protected:charPname[20]//姓名intPyear//

C++中关于读取文件的疑惑。。。
定义一个类    


class   Person     //基本资料
{
protected:
char   Pname[20];   //姓名
int   Pyear;   //出生年月
int   Pmonth;
char   Psex;   //性别
int   Pday;
char   Paddr[20];   //住址
long   int   Pphone;   //联系电话
public:
Person(string   name= "none ",   char   sex= '? ',int   y=0,   int   m=0,int   d=0,string   addr= "none ",long   int   phone=0);
friend   std::ostream   &   operator < <(std::ostream   &os,const     Person   &p)   ;
};

类实现

Person::Person(string   name,   char   sex,   int   y   ,   int   m,   int   d,string   addr,   long   phone)
{
strncpy(Pname,name.c_str(),19);
Pname[19]= '0 ';
Psex=sex;
Pyear=y;
Pmonth=m;
Pday=d;
strncpy(Paddr,addr.c_str(),19);
Paddr[19]= '0 ';
Pphone=phone;
}

std::ostream   &   operator < <(std::ostream   &os,   const   Person   &p)
{
os < < "\t姓名: " < <p.Pname;
os < < "\t性别: " < <p.Psex < <endl;
os < < "联系电话: " < <p.Pphone;
os < < "出生年月: " < <p.Pyear < < "/ " < <p.Pmonth < < "/ " < <p.Pday;
os < < "\t住址: " < <p.Paddr < <endl;
return   os;
}


主函数:

int   main()
{
Person   s[3]=
{
Person( "zmx ", 'm ',1987,06,8, "fuzhou ",5210269),
Person( "zhl ", 'f ',1988,02,10, "quanzhou ",5239448),
Person( "zll ", 'm ',1988,02,10, "quanfu ",110)
};
ofstream   OutFile;
OutFile.open( "saleman.dat ",ios::app|ios::binary);
for(int   i=0;i <3;++i)
OutFile.write((char   *)&s[i],sizeof(Person));
OutFile.close();
ifstream   InFile;
InFile.open( "saleman.dat ",ios::binary);
Person   a[3];
for(int   i=0;i <3;++i)
{
InFile.seekg(i*sizeof(Person),ios::beg);
InFile.read((char   *)&a[i],sizeof(Person));
cout < <a[i];
}
InFile.close();
system( "pause ");
return   0;
}

第一次运行的时候没有错,第二次运行的时候将一些参数修改一下就出错了

第二次运行时候的参数
int   main()
{
Person   s[3]=
{
Person( "zzz ", 'm ',1987,06,8, "fuzhou ",5210269),
Person( "zhl ", 'f ',1988,02,10, "quanzhou ",5239448),
Person( "zll ", 'm ',1988,02,10, "quanfu ",110)
};
ofstream   OutFile;
OutFile.open( "saleman.dat ",ios::app|ios::binary);
for(int   i=0;i <3;++i)
OutFile.write((char   *)&s[i],sizeof(Person));
OutFile.close();
ifstream   InFile;
InFile.open( "saleman.dat ",ios::binary);
Person   a[3];
for(int   i=0;i <6;++i)
{
InFile.seekg(i*sizeof(Person),ios::beg);
InFile.read((char   *)&a[i],sizeof(Person));
cout < <a[i];
}
InFile.close();
system( "pause ");
return   0;
}

请问如何才能在文件末端添加数据而且读取数据的时候不会出现错误??

------解决方案--------------------


Person a[3];//a[6]吧?
for(int i=0;i <3;++i)
{
InFile.seekg(i*sizeof(Person),ios::beg);
InFile.read((char *)&a[i],sizeof(Person));
cout < <a[i];
}

热点排行