C++文件操作
- C++对于文件操作需要导入头文件<fstream>
- 操作文件三大类
- ofstream:写操作
- ifstream:读操作
- fstrem:读写操作
- 文件类型
- 文本文件
- 二进制文件
文本文件
-
1.写文件
- 步骤
- 1导入头文件
#include <fstream> - 2创建流对象
ofstream ofs; - 3打开文件
ofs.open(“文件路径”,打开方式); - 4写入数据
ofs << “数据内容”; - 5关闭文件
ofs.close();
- 1导入头文件
- 打开方式
多个打开方式可以同时使用,以|隔开,如ios::binary|ios::out
注:不同的读写对象下,上述打开方式的效果不一定一致,可参考这里
打开方式 说明 ios::in 只读 ios::out 只写 ios::ate 初始指针在文件尾 ios::app 在文件尾追加数据 ios::trunc 如果文件存在,先删除 ios::binary 二进制方式 - 示例
#include<iostream> using namespace std; #include <string> #include <fstream> int main(){ //创建流对象 ofstream ofs; //打开文件 ofs.open(文件路径,打开方式); //写入 ofs << "bbbcccb\n"; //关闭文件 ofs.close(); return 0; }
- 步骤
-
2.读文件
- 步骤
-
1导入头文件
#include <fstream> -
2创建流对象
ifstream ifs; -
3打开文件并判断文件是否打开成功
ifs.open(“文件路径”,打开方式); -
4读取数据
-
5关闭文件
ifs.close();
-
- 示例
#include<iostream> using namespace std; #include <string> #include <fstream> int main(){ ifstream ifs; //打开文件 ifs.open(文件路径,打开方式); //判断是否成功 if(!ifs.is_open()){ cout << "文件打开失败" << endl; return 0; } //读取方法1 char buf1[1024] = {0}; while(ifs >> buf1){ //使用右移运算,将文件一行一行赋值给buf1变量 cout << buf1 <<endl; } //读取方法2 char buf2[1024] = {0}; while(ifs.getline(buf2,sizeof(buf2))){ //使用ifs对象的getline方法,一行一行读取数据 cout <<buf2 << endl; } //读取方法3 string buf3; while(getline(ifs,buf3)){ //使用全局函数getline,每次读取一行数据 cout << buf3 << endl; } //读取方法4 char s; while((s = ifs.get()) != EOF){ //EOF end of file 文件结束符 //ifs.get() 每次读取一个字符 cout << s <<endl; } ifs.close(); return 0; }
- 步骤
二进制文件
- 二进制除了存储常见的int,double,string等,还可存储诸如类等数据类型
- 1.写入
- 步骤
- 1.导入头文件
#include - 2.创建流对象
ofstream ofs; - 3.打开文件
ofs.open(文件,ios::out |ios::binary); - 4.写入文件
- 5.关闭文件
ofs.close();
- 1.导入头文件
#include<iostream> using namespace std; #include <string> #include <fstream> class Person{ public: void f(){ cout << "test" << endl; } }; int main(){ ofstream ofs; ofs.open(文件地址,ios::out| ios::binary); Person p; ofs.write((const char *)&p,sizeof(Person)); ofs.close(); return 0; }
- 步骤
- 2.读取
- 步骤
- 1.导入头文件
#include - 2.创建流对象
ifstream ifs; - 3.打开文件并判断是否打开成功
ifs.open(文件,ios::in |ios::binary); - 4.读取文件
- 5.关闭文件
ofs.close();
- 1.导入头文件
#include<iostream> using namespace std; #include <string> #include <fstream> class Person{ public: void f(){ cout << "test" << endl; } }; int main(){ ifstream ifs; //打开文件 ifs.open(文件地址,ios::in|ios::binary); //判断是否成功 if(!ifs.is_open()){ cout << "文件打开失败" << endl; return 0; } //读取文件 Person p; ifs.read((char *)&p,sizeof(Person)); p.f(); ifs.close(); }
- 步骤