c++对文件进行操作需要使用头文件<fstream>
文本文件:文件以文本的ASCII码形式存储在计算机中;
二进制文件:文件以文件的二进制存储在计算机中,用户一般不能直接读取它们
操作文件的三大类:
- ofstream:写
- ifstream:读
- fstream:读写
写文本文件步骤:包含头文件:#include<ftream>、创建流对象:ofstream ofs;、打开文件:ofs.open(文本路径,打开方式)、写数据:ofs<<数据、关闭文件:ofs.close()
文件打开的几种方式:
打开方式 | 解释 |
ios:in | 为读文件而打开 |
ios:out | 为写文件而打开 |
ios:ate | 初始位置:文件尾部 |
ios:app | 追加方式写文件 |
ios:trunc | 如果文件存在先删除,再创建 |
ios:binary | 二进制方式 |
写文件:
#include<iostream> #include<fstream> using namespace std; void test() { ofstream ofs; //如若不指定路径,则在该项目同级下生成 ofs.open("test.txt", ios::out); ofs << "hello world"<<endl; ofs << "tom" << endl; ofs.close(); } int main() { test(); system("pause"); return 0; }