一杯清酒邀明月
天下本无事,庸人扰之而烦耳。
ifream与ofream分别为文件读取类和文件写入类

实例1:文件读取(读取同一文件夹的test.txt文件内容)

 1 #include <fstream>// 涉及到了文件流操作 
 2 #include <iostream>
 3 
 4 using namespace std;
 5 
 6 int main()// in输入:读     out输出:写 
 7 {
 8       ifstream in;// 用ifstream(文件读取类)这个类定义in这个对象,所以in拥有了这个对象所有功能性质 
 9       
10       in.open( "test.txt" );// 打开这个文件 
11       if( !in )// 打开失败 
12       {
13             cerr << "打开文件失败" << endl;
14         return 0;
15       }
16 
17       char x;
18       while( in >> x )//文件in流到字符x中去,每次流一个字符 
19       {
20             cout << x;
21       }
22 
23       cout << endl;
24       in.close();//关闭文件 
25 
26       return 0;
27 }

实例2:将0-9写入到同一文件夹的test.txt文件

 1 #include <fstream>//涉及到了文件流操作 
 2 #include <iostream>
 3 
 4 using namespace std;
 5 
 6 int main()
 7 {
 8       ofstream out;//ofstream(文件输出类,写文件)
 9 
10       out.open( "test.txt" );
11       if( !out )
12       {
13             cerr << "打开文件失败!" << endl;
14             return 0;
15       }
16 
17       for( int i=0; i < 10; i++ )
18       {
19             out << i;
20       }
21       
22       out << endl;
23       out.close();
24 
25       return 0;
26 }

实例3:以添加形式将10-0写入test.txt文件

 1 #include <fstream>
 2 #include <iostream>
 3 
 4 using namespace std;
 5 
 6 int main()//ofstream 为构造函数 
 7 {
 8       ofstream out( "test.txt", ios::app );// app表示以添加形式(即不覆盖原数据)打开 
 9 
10       if( !out )
11       {
12             cerr << "文件打开失败!" << endl;
13             return 0;
14       }
15 
16       for( int i=10; i > 0; i-- )
17       {
18             out << i;
19       }
20 
21       out << endl;
22       out.close();
23 
24       return 0;
25 }

实例4:同时完成对test.txt的读写

 1 #include <fstream>
 2 #include <iostream>
 3 
 4 using namespace std;
 5 
 6 int main()
 7 {
 8       fstream fp("test.txt", ios::in | ios::out );
 9       if( !fp )
10       {
11             cerr << "打开文件失败!" << endl;
12             return 0;
13       }
14 
15       fp << "IloveFishc.com!IloveFishc.com!";
16 
17       static char str[100]; 
18 
19       fp.seekg(ios::beg); //使得文件指针指向文件头   ios::end则是文件尾。
20       fp >> str;
21       cout << str << endl;
22 
23       fp.close();
24 
25       return 0;
26 }

作业:将text1.txt文件内容复制到text2.txt中

 1 #include <fstream>//涉及到了文件流操作 
 2 #include <iostream>
 3 
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     ifstream in;
 9     ofstream out;
10     char x;
11     in.open("text1.txt");
12     out.open("text2.txt");
13     while(!in)
14              {
15                  cout<<"源文件打开失败,请重新输入路径:";
16                  return 0;
17               }
18      while(!out)
19              {
20                  cout<<"目标文件失败,请重新输入路径:";
21                  return 0;
22              }
23     while(in>>x)
24         {
25                   out<<x;
26          }
27      out<<endl;
28      in.close();//关闭文件 
29      out.close();//关闭文件 
30      system("pause");
31      return 0;
32 
33 }
posted on 2023-08-18 14:03  一杯清酒邀明月  阅读(57)  评论(0编辑  收藏  举报