C/C++文件流
文件流是以外存文件为输入/输出对象的数据流。输出文件流是从内存流向外存文件的数据,输入文件流是从外存文件流向内存的数据。每一个文件都有一个内存缓冲区与之对应。这里主要讨论两种文件的操作。
3.3.1 ASCII 文件的操作
程序描述:从键盘读入一行字符,把其中的字母字符依次存放在磁盘文件f2.dat 中,再将此磁盘文件读入程序,将其中的小写字母改为大写字母,并存入磁盘文件f3.dat。
【源程序 3-3】
01 #include <fstream> 02 using namespace std; 03 void save_to_file() 04 { 05 ofstream outfile("f2.dat",ios::out); 06 if(!outfile) 07 { 08 cerr<<"open f2.dat error!"<<endl; 09 exit(1); //退出程序 10 } 11 char c[80]; 12 cin.getline(c,80); //从键盘读入一行字符 13 for(int i=0;c[i]!=0;i++) 14 if(c[i]>=65&&c[i]<=90||c[i]>=97&&c[i]<=122) 15 { 16 outfile.put(c[i]); //将字母字符存入磁盘文件f2.dat 17 cout<<c[i]; //输出到显示器显示 18 } 19 cout<<endl; 20 outfile.close(); //关闭f2.dat 文件 21 } 22 void get_from_file() 23 { 24 char ch; 25 ifstream infile("f2.dat",ios::in|ios::nocreate); 26 if(!infile) 27 { 28 cerr<<"open f2.dat error!"<<endl; 29 exit(1); 30 } 31 ofstream outfile("f3.dat"); 32 if(!outfile) 33 { 34 cerr<<"open f3.dat error!"<<endl; 35 exit(1); 36 } 37 while(infile.get(ch)) //流成员函数get 读入一个字符 38 { 39 if(ch>=97&&ch<=122) //判断是否为小写字母 40 ch=ch-32; 41 outfile.put(ch); //流成员函数put 输出字符存入f3.dat 42 cout<<ch; 43 } 44 cout<<endl; 45 infile.close(); //关闭磁盘文件f2.dat 46 outfile.close(); //关闭磁盘文件f3.dat 47 } 48 int main() 49 { 50 save_to_file(); 51 get_from_file(); 52 return 0; 53 } |
01 #include <fstream> 02 using namespace std; 03 struct student 04 { 05 string name; 06 int num; 07 int age; 08 char sex; 09 }; 10 int main() 11 { 12 student stud[3]; 13 int i; 14 ifstream infile("stud.dat",ios::binary); 15 if(!infile) 16 { 17 cerr<<"open error!"<<endl; 18 abort(); 19 } 20 for(i=0;i<3;i++) 21 infile.read((char*)&stud[i],sizeof(stud[i])); 22 infile.close(); 23 for(i=0;i<3;i++) 24 { 25 cout<<"NO."<<i+1<<endl; 26 cout<<"name:"<<stud[i].name<<endl; 27 cout<<"num:"<<stud[i].num<<endl; 28 cout<<"age:"<<stud[i].age<<endl; 29 cout<<"sex:"<<stud[i].sex<<endl<<endl; 30 } 31 return 0; 32 } |
联系客服