在程序运行时产生的数据都属于临时数据,程序一结束就代表着临时数据将被释放,为此可以通过文件将数据持久化(数据保存)。
C++中对文件进行操作则需要添加头文件 #include <fstream>
文件类型分为两种:
1、文本文件 -文件以文本的ASCII码形式存储在计算机中.
2、二进制文件 -文件以文本的二进制形式存储在计算机中,用户一般不能直接读懂它们。
操作文件的三大类:
1、ofstream 写操作 2、ifstream 读操作 3、fstream 读写操作
1、文本文件的读写
写文件步骤流程:
1、添加头文件 #include <fstream>
2、创建流对象 ofstream 流名称;
3、打开文件 流名称.open("文件路径","打开方式");
4、写数据 流名称 << "写入的数据"
5、关闭文件 流名称.close();
文件打开方式:
如果打开方式需要配合使用,则需要利用“ | ”操作符
打开方式 解释 ios::in 以读文件方式打开文件
ios::out 以写文件方式打开文件 ios::ate 初始位置:文件尾 ios::app 追加方式写文件 ios::trunc 如果文件存在先删除,在创建 ios::binary 二进制方式
文件的路径:分为绝对路径和相对路径 绝对路径:从最上面开始一步一步往下面走。 如:D:\hqyj\notes\teacher\C++ 相对路径:就是程序本身所在的文件夹下
写操作示例:
#include <iostream>
#include <fstream>
using namespace std;
void writef()//往文件写操作
{
ofstream ofs;
ofs.open("文件路径", ios::out);
ofs << "写入数据" << endl;
ofs.close();
}
int main()
{
writef();
return 0;
}
读操作示例:
#include <iostream>
#include <fstream>
using namespace std;
void writef()//往文件写操作
{
ifstream ifs;
ifs.open("文件路径", ios::in);
if(!ifs.open())
{
cout << "打开失败" << endl; return ;
}
//四种读数据方法
char buf[1024]={0};
//第一中
while(ifs >> buf)
{
cout << buf << endl;
}
//第二种
while(ifs.getline(buf,zizeof(buf)))//fstream函数
{
cout << buf << endl;
}
//第三种
string buf1;
while(getline(ifs,buf1))
{
cout << buf << endl;
}
//第四种(不推荐)
char c;
while((c=ifs.get) != EOF)
{
cout << c;
}
ifs.close();
}
int main()
{
writef();
return 0;
}
二进制文件-写操作;
class Person { public: char m_Name[64]; int m_Age; }; int main() { ofstream ofs("文件路径及名称",ios::out | ios::binary) Person p = {"张三",18}; ofs.write((const char*)&p,sizeof(Person)); ofs.close(); return 0; }
二进制文件-读操作;
class Person { public: char m_Name[64];//姓名 int m_Age; }; int main() { ifstream ifs("文件路径及名称",ios::in | ios::binary); if(!(fs.open()) { cout << "打开失败" << endl; return ; } Person p = {"张三",18}; ifs.read((const char*)&p,sizeof(Person));//已读到 cout << "姓名" << p.m_Name << endl; ifs.close(); return 0; }