|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 这是她 于 2020-5-23 22:16 编辑
He who would travel happily must travel light.
文件
文件可以使数据持久化
C++对文件操作需要包含头文件<fstream>
文件类型:文本文件 二进制文件
操作文件的三大类:
1、ofstream:写操作
2、ifstream:读操作
3、fstream:读写操作
文本文件 ---文件以文本的ASCLL码形式存储在计算机中
写文件:
1、包含头文件:#include<fstream>
2、创建流对象:ofstream ofs;
3、打开文件:ofs.open("文件的路径",打开方式);
4、写数据:ofs<<"写入的数据";
5、关闭文件:ofs.close();
文件打开方式:
ios::in->为读文件而打开文件
ios::out ->为写文件而打开文件
ios::ate->初始位置:文件尾
ios::app->追加方式写文件
ios::trunc->如果文件存在先删除,在创建
ios::binary->二进制
- #include<iostream>
- #include<fstream>//头文件
- using namespace std;
- void test()
- {
- //创建流对象
- ofstream p1;
-
- //指定打开方式
- p1.open("test1.txt",ios::out);
-
- //写入内容
- p1 << "你站在桥上看风景,看风景的人在楼上看你" << endl;
- p1 << "明月装饰了你的窗子,你装饰了别人的梦" << endl;
-
- //关闭文件
- p1.close();
- }
- int main()
- {
- test();
-
- return 0;
- }
复制代码 读文件:
1、包含头文件 #include <fstream>
2、创建流对象 ifstream ifs;
3、打开文件并判断文件是否打开成功 ifs.open("文件路径",打开方式);
4、读数据 四种方式读取
5、关闭文件 ifs.close();
- #include<iostream>
- #include<string>
- #include<fstream>//头文件
- using namespace std;
- void test()
- {
- //创建流对象
- ifstream p1;
-
- //打开文件,并且判断是否打开成功
- p1.open("test1.txt",ios::in);
-
- if (!p1.is_open())
- {
- cout << "文件打开失败!!!" << endl;
- return;
- }
-
- //读数据
-
- //第一种
- //存放在一个字符数组中,输出
- char a[1024] = { 0 };
- while(p1 >> a )//while循环,输出--文件内容;
- {
- cout << a << endl;
- }
- //第二种
- char a[1024] = { 0 };
- while (p1.getline(a,sizeof(a))) //getline是一行一行的读取
- {
- cout << a << endl;
- }
- //第三种
- string a;
- while (getline(p1,a))
- {
- cout << a << endl;
- }
- //第四种
- char b;
- while ( (b = p1.get()) != EOF )//EOF->文件结束符
- {
- cout << b;
- }
- //关闭文件
- p1.close();
- }
- int main()
- {
- test();
-
- return 0;
- }
复制代码
渣渣一个 望各位大佬指教
|
|