文件操作
C++中提供了文件流来对文件进行操作
需要引入头文件fstream
文件类型:
- 文本文件:以ASCII码存储
- 二进制文件:以二进制形式存储
操作文件三大类:
- ofstream:写
- ifstream:读
- fstream:读/写
文本文件
写文件
1 2 3 4 5 6 7 8
| #include <fstream> using namespace std; int main(){ ofstream ofs; ofs.open("路径", <打开方式>) ofs << "写入的数据"; ofs.close(); }
|
其中打开方式有:
| 打开方式 |
解释 |
| ios::in |
读文件而打开文件 |
| ios::out |
写文件而打开文件 |
| ios::ate |
文件打开时指针位于文件末尾,可以移动指针进行读写 |
| ios::app |
所有读写操作都会添加到文件末尾 |
| ios::trunc |
若文件存在则先删除再创建 |
| ios::binary |
二进制方式操作 |
可以使用|操作符来配合使用多个文件操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| #include<iostream> #include<fstream> using namespace std; int main(){ ofstream ofs; ofs.open("test.txt", ios::out); ofs << "name: Li Hua"<<endl; ofs << "age: male"<<endl; ofs.close(); }
|
读文件
1 2 3 4 5 6 7 8
| #include <fstream> using namespace std; int main(){ ifstream ofs; ofs.open("路径", <打开方式>) ofs << "写入的数据"; ofs.close(); }
|
其中读取数据有多种方式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| #include<iostream> #include<fstream> #include <string> using namespace std; int main(){ ifstream ifs; ifs.open("test.txt", ios::in); if(!ifs.is_open()){ cout <<"Open failed"; return 0; } char buf[1024]={}; while(ifs>>buf){ cout << buf << endl; }
char buf2[1024]={}; while(ifs.getline(buf2, sizeof buf2)){ cout << buf << endl; }
string bufs; while(getline(ifs, bufs)){ cout << buf << endl; }
char c; while((c=ifs.get())!=EOF){ cout << c; } ifs.close();
}
|
二进制文件
二进制打开方式指定为ios::binary
写文件
注意:写入二进制文件时,不建议使用string,会引发指针异常
使用write方式来写入文件,而不是用流式输入,对一个对象我们使用const char*这样一个常量指针类型取得对象实例地址后进行写入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| #include<iostream> #include<fstream> using namespace std; class person{ public: char name[64]; int age; }; int main(){ ofstream ofs; ofs.open("person.txt", ios::out|ios::binary); person p = {"Jack", 18}; ofs.write((const char*)&p, sizeof(person)); ofs.close(); }
|
读文件
使用read方式来读文件
参数原型:istream& read(char *buffer, int len);
即字符指针buffer指向内存中一段存储空间,len为读写的字节数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| #include<iostream> #include<fstream> using namespace std; class person{ public: char name[64]; int age; };
int main(){ ifstream ifs; ifs.open("person.txt", ios::in|ios::binary); if(!ifs.is_open()){ cout <<"Open failed"; return 0; } person p; ifs.read((char *)&p, sizeof(person)); cout << "name: "<<p.name<<endl; cout << "age: "<<p.age<<endl;
ifs.close(); }
|