示例:将数据写入ASCII文件
#include <iostream> #include <fstream> #include <cstdlib> using namespace std; int main( ) { int a[10]; ofstream outfile("f1.dat",ios::out);//定义文件流对象,打开磁盘文件"f1.dat" if(!outfile) //如果打开失败,outfile返回0值 { cerr<<"open error!"<<endl; exit(1); } cout<<"enter 10 integer numbers:"<<endl; for(int i=0; i<10; i++) //向磁盘文件"f1.dat"输出数据 { cin>>a[i]; outfile<<a[i]<<" "; } cout<<"The numbers have been writen to file. "<<endl; outfile.close(); //关闭磁盘文件"f1.dat" return 0; }
示例:从ASCII文件读入数据
#include <iostream> #include <fstream> #include <cstdlib> using namespace std; int main( ) { int a[10],max,i,order; ifstream infile("f1.dat",ios::in); //定义输入文件流对象,以输入方式打开磁盘文件f1.dat if(!infile) { cerr<<"open error!"<<endl; exit(1); } for(i=0; i<10; i++) { infile>>a[i]; //从磁盘文件读入10个整数,顺序存放在a数组中 cout<<a[i]<<" "; } //在显示器上顺序显示10个数 cout<<endl; max=a[0]; order=0; for(i=1; i<10; i++) if(a[i]>max) { max=a[i]; //将当前最大值放在max中 order=i; //将当前最大值的元素序号放在order中 } cout<<"max="<<max<<endl<<"order="<<order<<endl; infile.close(); return 0; }
示例:读写ASCII文件
#include<iostream> #include <fstream> #include <cstdlib> using namespace std; void save_to_file( ); void get_from_file(); int main( ) { save_to_file( ); get_from_file( ); return 0; } void save_to_file( ) { ofstream outfile("f2.dat"); if(!outfile) { cerr<<"open f2.dat error!"<<endl; exit(1); } char c[80]; cin.getline(c,80); for(int i=0; c[i]!=0; i++) if(c[i]>='a' && c[i]<='z') outfile.put(c[i]); outfile.close(); } void get_from_file() { char ch; ifstream infile("f2.dat",ios::in); if(!infile) { cerr<<"open f2.dat error!"<<endl; exit(1); } ofstream outfile("f3.dat"); if(!outfile) { cerr<<"open f3.dat error!"<<endl; exit(1); } while(infile.get(ch)) outfile.put(ch-32); infile.close( ); outfile.close(); }
示例:在显示器上输出文件
#include <iostream> #include <fstream> #include <cstdlib> using namespace std; void display_file(char *filename); int main( ) { display_file("f3.dat"); return 0; } void display_file(char *filename) { ifstream infile(filename,ios::in); if(!infile) { cerr<<"open error!"<<endl; exit(1); } char ch; while(infile.get(ch)) cout.put(ch); cout<<endl; infile.close(); }