- 3
- 0
- 约2.89万字
- 约 79页
- 2019-11-06 发布于广东
- 举报
dfile.open(filename,ios::out); if(!dfile){ cout目标文件创建失败endl; return -1;} while(sfile.getline(buf,100),sfile.eof()!=1){ //按行复制 A行 if(sfile.rdstate()==0) dfilebuf\n; //因读到回车符,提取但未保存 B行 else {dfilebuf; sfile.clear(0);} } //流不正常, //还未读到回车换行符,所以不加‘\n’ 。状态字被置为failbit,必须清0 sfile.close(); dfile.close(); return 0;} A行中sfile.getline(buf,100)从源文件读一行字符,或读99个字符,效率大大提高。B行中,因从源文件读字符是遇到行结束(回车换行)符停止的,所以文件中应有一个回车换行符;但getline()回车换行符并不放在buf中,因此要加一个回车换行符,但此程序只能用于文本文件。 9.4.2 文本文件的读写 【例9.9】文本式数据文件的创建与读取数据。典型的C++数据存入文件和由文件获得数据的方法是把对象存入文件和由文件重构对象。本例对提取和插入运算符进行了重载,只用一个“”完成重构对象,而只用一个“”完成对象存入文件。 class inventory{ string Description; string No; int Quantity; double Cost; double Retail; public: inventory(string=#,string=0,int=0,double=0,double=0); friend ostreamoperator(ostreamdest,inventoryiv); friend istreamoperator(istreamsour,inventoryiv); }; //流类作为形式参数必须是引用 9.4.2 文本文件的读写 inventory::inventory(string des,string no,int quan, double cost,double ret){ Description=des; No=no; Quantity=quan; Cost=cost; Retail=ret;} ostream operator(ostreamdest,inventoryiv){ destleftsetw(20)iv.Descriptionsetw(10)iv.No; destrightsetw(10)iv.Quantitysetw(10)iv.Cost setw(10)iv.Retailendl; return dest; } //写入文件是自动把数转为数字串后写入, //数字串必须相互分隔,否则读取时无法区分 istreamoperator(istreamsour,inventoryiv){ souriv.Descriptioniv.Noiv.Quantity iv.Costiv.Retail; return sour; } //从文件读出是自动把数字串转为数读出, //函数体内功能不变,会自动转换 9.4.2 文本文件的读写 int main(){ inventory car1(夏利2000,805637928,156,80000,105000),car2; inventory motor1(金城125302,10000,13000),motor2; ofstream destfile(d:\\Ex9_9.data); destfilecar1motor1; //注意ofstream是ostream的派生类 destfile.close(); coutcar1; coutmotor1; coutcar2; coutmotor2; ifstream sourfile(d:\\Ex9_9.data); //这样分两次打开,可避免读文件时,误改了源文件 sourfilecar2motor2; sourfile.clos
原创力文档

文档评论(0)