知识点介绍:
程序运行时产生的数据都属于临时数据,程序一旦运行结束都会被释放
通过文件可以将数据持久化
c++中对文件的操作需要包含头文件 <fstream>
文本文件分为两种:
1.文本文件 文件以文本的ASCLL码形式存储在计算机中
2.二进制文件 文件以文本的二进制形式存储在计算机中 用户一般不能直接读懂他们
操作文件的三大类:
1.ofstaeam 写操作
2.ifstream 读操作
3.fstram 读写操作
文件打开方式:
1. ios::in为读文件而打开文件
2. ios::out 为写文件而打开文件
3. ios::ate 初始位置:文件尾
4. ios::trunc 如果文件存在 先删除 再创建
5. ios::binary 二进制方式
一 .文本文件操作
1.写文件
//文本文件 写文件
#include<iostream>
using namespace std;
#include<fstream>
void test()
{
//1.包含头文件<fstream>
//2.创建流对象
ofstream ofs;
//3.指定打开方式
//调用open函数
//open(const char *_Filename, std::ios_base::openmode _Mode,int _Prot = 64)
//open函数的参数(文本路径,打开方式)
ofs.open("test.txt", ios::out);
//4.写内容
ofs << "姓名:张三" << endl;
ofs << "年龄:18" << endl;
ofs << "性别:男" << endl;
//5.关闭文件
ofs.close();
}
int main()
{
test();
system("pause");
return 0;
}
运行结果为:
注意:open(const char *_Filename, std::ios_base::openmode _Mode,int _Prot = 64)
open(文本路径,打开方式) 既可以写文本的路径 也可以直接写文件名 会默认指向与源文件最近的文件
此时传入了文本文件之中 无法显示 可以从打开文本文件查看内容:
2.读文件
#include<iostream>
using namespace std; //读文件
#include<fstream>
#include<string>
void test()
{
//1.包含头文件
//2.创建流对象
ifstream ifs;
//3.打开文件 并且判断是否成功
ifs.open("test.txt", ios::in);
//成员函数is_open 作用:是否打开文件成功 为bool类型
if (!ifs.is_open())
{
cout << "打开文件失败" << endl;
return;
}
//4.读数据
//定义一个字符串变量
string buf;
//调用getline函数得到文件数据并传给buf字符串变量 在此之前 必须包含头文件 <string>
while (getline(ifs, buf))
{
//将buf变量的数据输出
cout << buf << endl;
}
//5.关闭文件
ifs.close();
}
int main()
{
test();
system("pause");
return 0;
}
运行结果:
注意:getline(std::istream &_Istr, std::string &_Str) getline(流对象,字符串变量) 返回的是bool类型
二. 二进制文件操作
1.写文件
//写文件
#include<iostream>
using namespace std;
#include<fstream>
//定义一个person类
class person
{
public:
char m_Name[64]; //二进制方式里 用c++里的string类型 会出现问题 所以用 char型代替
int m_Age;
};
void test()
{
//1.包含头文件
//2.创建流对象
ofstream ofs;
//3.打开文件
ofs.open("test.txt", ios::out | ios::binary);
//需用换位符"|" 加入 binary 表示也使用了二进制
//4.写文件
//初始化对象数据
person p = {"李四",20};
ofs.write((const char*)&p, sizeof(person));
//关键: 指出p的地址 &p 此时为 person * 类型 要强转为const char * 类型
//5.关闭文件
ofs.close();
}
int main()
{
test();
system("pause");
return 0;
}
通过文本文件查看内容:
此时既有文本文件方式 也有二进制方式 二进制方式为乱码无法直接看出
运行结果:
注意:二进制方式写文件主要利用流对象调用成员函数 write
函数原型 ostream& write(const char * buffer,int len) buffer:缓冲区
参数解释 字符指针buffer指向内存中一段储存空间,len是读写的字节数
2.读文件
//读文件
#include<iostream>
using namespace std;
#include<fstream>
//定义一个person类
class person
{
public:
char m_Name[64];
int m_Age;
};
void test()
{
//1.包含头文件
//2.创建流对象
ifstream ifs;
//3.打开文件 并判断是否成功
ifs.open("test.txt", ios::in | ios::binary);
//需用换位符"|" 加入 binary 表示也使用了二进制
if (!ifs.is_open())
{
cout << "打开文件失败" << endl;
return;
}
//4.读文件
//创建对象p
person p;
ifs.read((char*)&p, sizeof(person));
//关键: 指出p的地址 &p 此时为 person * 类型 要强转为 char * 类型
//将文件数据传入给p 并将p的数据输出
cout << "姓名:" << p.m_Name << "年龄:" << p.m_Age << endl;
//5.关闭文件
ifs.close();
}
int main()
{
test();
system("pause");
return 0;
}
运行结果:
注意:二进制方式读文件主要利用流对象调用成员函数 read
函数原型 ostream& read(char * buffer,int len) buffer:缓冲区
参数解释 字符指针buffer指向内存中一段储存空间,len是读写的字节数