C++文件操作
程序运行时产生的数据属于临时数据,程序一旦运行结束都会被释放,通过文件可以将数据持久化。
C++中对文件操作需要包含头文件 #include<fstream>
文件类型 文本文件ASCII码形式储存 二进制文件二进制形式存储
操作文件三大类 ofstream 写操作 ifstream读操作 fstream读写操作
文本文件流程:
包含头文件 --->#include<fstream> 创建流对象 ofstream ofs;--->打开文件ofs.open("文件路径",打开方式)--->写数据 ofs<<"写入的数据"--->关闭文件 ofs.close();
打开方式:
ios::in 为读文件而打开
ios::out 为写文件而打开
ios::binary 二进制方式 可以配合使用,利用|操作符 ios::binary | ios::out
目录
写文件:
(如果没有该文件名 的文件,会自动创建一个该文件名的文件,写入)
#include<iostream>
#include<ofstream>//1.包含头文件
#include<stream>
using namespace std;
//写文件
void test01()
{
//2.创建流对象
ofstream ofs;
//3.打开文件 并 选择打开方式
ofs.open("File.txt" , ios::out );
//4.写入数据
ofs << "姓名:张三" << endl;
ofs << "性别:男" << endl;
ofs << "年龄:23" << endl;
// 5.关闭文件
ofs.close();
}
int main()
{
system("pause");
return 0 ;
}
读文件
#include<iostream>
#include<ofstream>//1.包含头文件
#include<stream>
using namespace std;
//写文件
void test01()
{
//2.创建流对象
ifstream ifs;
//3.打开文件 并 选择打开方式
ifs.open("File.txt" , ios::in );
//4.读数据 , 先判断文件是否存在
if(!ifs.is_open())
{
cout << "文件不存在"<<endl;
return ;
}
else
{
//三种方式读文件
char buf[1024] = {0};
while (ifs >> buf) // 按字符串读取
{
cout << buf << endl;
}
//2
char buf[1024] = {0};
while (ifs.getline(buf , sizeof(buf)))//按行读取
{
cout << buf << endl;
}
//3 老师说不推荐该方式 , 速度慢
char c;
while((c = ifs.get()) != EOF) // EOF end of line
{
cout << c;
}
ifs.close();
}
}
int main()
{
system("pause");
return 0 ;
}
二进制文件 写文件
打开文件方式要指定为ios::binary
class Person
{
public:
char m_Name[64];
int m_Age;
};
void test03()
{
ofstream ofs("Person.txt", ios::out | ios::binary);
//ofs.open("Person.text", ios::out | ios::binary);
Person p = { "张三", 23 };
ofs.write((const char*)&p, sizeof(Person));
ofs.close();
}
二进制文件 写文件
istream& read(char *buffer , int len) 字符指针buffer指向内存中一段存储空间,len时读写的字节数
void test04()
{
ifstream ifs;
ifs.open("Person.txt", ios::in | ios::binary);
if (!ifs.is_open())
{
cout << "文件打开失败" << endl;
return;
}
Person p;
ifs.read((char*)&p, sizeof(Person));
cout << "姓名:" << p.m_Name << " 年龄 = " << p.m_Age;
ifs.close();
}
这部分说实话有点懵,需要多记一下