C++文件操作
时间:2010-06-01 来源:mengl_08
源代码:
#include<iostream.h> #include<fstream.h> #include<stdlib.h> struct worker { char name[30]; char department[30]; float basepay,allowance,total; }; void main() { char filename[30]="paydata.txt"; struct worker data; ofstream outstuf; outstuf.open(filename,ios::out|ios::binary); if(!outstuf) { cout<<"打开文件失败!"<<endl; abort(); } outstuf<<"这是一个和工人工资有关的文件.\n"<<endl; char ch='N'; while(ch!='y'&&ch!='Y') { cout<<"请输入工人名字,工人住址及其基本工资和奖金:"<<endl; cin>>data.name>>data.department>>data.basepay>>data.allowance;//插入数据 outstuf<<data.name<<data.department<<data.basepay<<' '<<data.allowance<<' '<<(data.total=data.basepay+data.allowance)<<'\n'; cout<<"是否结束输入?Y or N?"<<endl; cin>>ch; } outstuf.close(); //以下为改动操作********* ifstream instuf; instuf.open(filename,ios::in|ios::binary); if(!instuf) { cout<<"文件打开失败,程序退出!"<<endl; abort(); } instuf.clear(); int i=0; while(!instuf.eof()) { instuf>>data.name>>data.department>>data.basepay>>data.allowance>>data.total; data.basepay=data.basepay+100;; data.total=data.total+100; cout<<"现在输出工人的名字、住址、基本工资、奖金、总共资金:"<<endl; cout<<data.name<<'\t'<<data.department<<'\t'<<data.basepay<<'\t'<<data.allowance<<'\t'<<data.total<<endl; i++; } instuf.close(); }
#include<iostream.h> #include<fstream.h> #include<stdlib.h> struct worker { char name[30]; char department[30]; float basepay,allowance,total; }; void main() { char filename[30]="paydata.txt"; struct worker data; ofstream outstuf; outstuf.open(filename,ios::out|ios::binary); if(!outstuf) { cout<<"打开文件失败!"<<endl; abort(); } outstuf<<"这是一个和工人工资有关的文件.\n"<<endl; char ch='N'; while(ch!='y'&&ch!='Y') { cout<<"请输入工人名字,工人住址及其基本工资和奖金:"<<endl; cin>>data.name>>data.department>>data.basepay>>data.allowance;//插入数据 outstuf<<data.name<<data.department<<data.basepay<<' '<<data.allowance<<' '<<(data.total=data.basepay+data.allowance)<<'\n'; cout<<"是否结束输入?Y or N?"<<endl; cin>>ch; } outstuf.close(); //以下为改动操作********* ifstream instuf; instuf.open(filename,ios::in|ios::binary); if(!instuf) { cout<<"文件打开失败,程序退出!"<<endl; abort(); } instuf.clear(); int i=0; while(!instuf.eof()) { instuf>>data.name>>data.department>>data.basepay>>data.allowance>>data.total; data.basepay=data.basepay+100;; data.total=data.total+100; cout<<"现在输出工人的名字、住址、基本工资、奖金、总共资金:"<<endl; cout<<data.name<<'\t'<<data.department<<'\t'<<data.basepay<<'\t'<<data.allowance<<'\t'<<data.total<<endl; i++; } instuf.close(); }
相关阅读 更多 +