程序运行时产生的数据都属于临时数据,程序一旦运行结束就会被释放,通过文件可以使数据持久化。
C++中对文件操作需要包含头文件
(文件流)
文本文件:文件以文本的ASCII码形式存储在计算机中
二进制文件:文件以文本的二进制形式存储在计算机中,用户一般不能直接读懂
文件操作主要分三大类:
步骤:
#include
ofstream ofs;
ofs.open("文件路径(即指向文件名的指针)",打开方式);
ofs << "写入的数据";
ofs.close();
PS:创建流对象和文件的打开可和为一部,用ofs的构造函数
ofstream ofs("文件路径(即指向文件名的指针)",打开方式);
C++中文件打开方式:
步骤:
#include
ifstream ifs;
ifs.open("test.txt",ios::in);
if (!ifs.is_open())
{
cout<<"文件打开失败"<<endl;
return;
}
第一种:字符数组
char buf[1024]={0};
while (ifs >> buf) //从ifs中存入字符数组buf中
{
cout<< buf << endl;
}
第二种:调用ifs.getline(const char buffer,int len)
函数
字符指针buffer指向内存中一段存储空间,len是读写的字节数
char buf[1024]={0};
while (ifs.getline(buf,sizeof(buf)))
{
cout<< buf << endl;
}
第三种:字符串+函数getline(输入流,字符串)
string buf;
while (getline(ifs,buf))
{
cout<< buf << endl;
}
第四种:字符单个输出(不推荐)
ifs.get()
:每次只读一个字符
char c;
while ((ifs.get())!=EOF) //判断未到文件结尾
{
cout<< c;
}
ifs.close();
以二进制方式对文件进行读写操作,打开方式要指定为ios::brinary
二进制方式写文件主要利用流对象调用成员函数write
函数:ostream& write(const char * buffer,int len);
include <fstream>
class Person
{
public:
char m_Name[64]; //此处建议用字符数组,不用字符串
int m_Age;
};
int main()
{
ofstream ofs("test.txt",ios::in | ios::binary);
Person p = {"张三",18};
ofs.write((const char*)&p,sizeof(Person));
ofs.close();
}
二进制方式写文件主要利用流对象调用成员函数read
函数:ostream& write(char * buffer,int len);
ofs.read((char *)&p,sizeof(Person));