C++快速入门 第四讲:文件操作


ifream与ofream分别为文件读取类和文件写入类

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

1 #include <fstream>// 涉及到了文件流操作 2 #include <iostream> 3 4 using namespace std; 5 6 int main()// in输入:读 out输出:写 7 16 17 char x; 18 while( in >> x )//文件in流到字符x中去,每次流一个字符 19 22 23 cout << endl; 24 inlose();//关闭文件 25 26 return 0; 27 }

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

1 #include <fstream>//涉及到了文件流操作 2 #include <iostream> 3 4 using namespace std; 5 6 int main() 7 16 17 for( int i=0; i < 10; i++ ) 18 21 22 out << endl; 23 outlose(); 24 25 return 0; 26 }

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

1 #include <fstream> 2 #include <iostream> 3 4 using namespace std; 5 6 int main()//ofstream 为构造函数 7 15 16 for( int i=10; i > 0; i ) 17 20 21 out << endl; 22 outlose(); 23 24 return 0; 25 }

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

1 #include <fstream> 2 #include <iostream> 3 4 using namespace std; 5 6 int main() 7 14 15 fp << "IloveFishc!IloveFishc!"; 16 17 static char str[100]; 18 19 fp.seekg(ios::beg); //使得文件指针指向文件头 ios::end则是文件尾。 20 fp >> str; 21 cout << str << endl; 22 23 fplose(); 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 18 while(!out) 19 23 while(in>>x) 24 27 out<<endl; 28 inlose();//关闭文件 29 outlose();//关闭文件 30 system("pause"); 31 return 0; 32 33 }


上一篇:C++快速入门 第三讲:输入输出方法

下一篇:C++快速入门 第十四节:对象


C/C&#x2B;&#x2B;
Copyright © 2002-2019 k262电脑网 www.k262.cn 皖ICP备2020016292号
温馨提示:部分文章图片数据来源与网络,仅供参考!版权归原作者所有,如有侵权请联系删除!QQ:251442993 热门搜索 网站地图