程序运行时产生的数据都属于临时数据,程序一旦运行结束都会释放
通过文件可以将数据持久化
c++中对文件操作需要包含头文件<fstream>(file stream 文件流)
文件类型分为两种
- 文本文件:文件以文本的ASCLL码形式存储在计算机中。
- 二进制文件:文件以文本的二进制形式存储在计算机中,用户一般不能直接读懂它们。
文件操作三大类:
- ofstream:写操作
- ifstream:读操作
- fstram:读写操作
文本文件
写文件
写文件步骤如下:
- 包含头文件:#include<fstream>
- 创建流对象:ofstream ofs; (out file stream 输出文件流类)
- 打开文件:ofs.open("文件路径", "打开方式");
- 写入数据:ofs<<"写入的数据";
- 关闭文件:ofs.close();
文件打开方式:
打开方式 | 解释 |
ios::in | 以读的方式打开文件 |
ios::out | 以写的方式打开文件 |
ios::ate | 打开文件的初始位置在文件尾 |
ios::app | 追加方式写文件 |
ios::trunc | 如果打开文件已存在,则先删除,再创建 |
ios::binary | 二进制方式 |
注意:文件的打开方式配合使用,使用 | 操作符
例如:用二进制方式写文件:ios::binary | ios::out
#include <iostream>
#include <fstream>
using namespace std;
void test()
{
ofstream ofs;
ofs.open("test.txt", ios::out);
ofs << "姓名:张三" << endl;
ofs << "性别:男" << endl;
ofs << "年龄:18" << endl;
ofs.close();
}
int main()
{
test();
return 0;
}
读文件
读文件与写文件步骤相似,但是读取方式相较于写文件更多
读文件步骤如下:
- 包含头文件:#include <fstream>
- 创建流对象:ifstream ifs;
- 打开文件并判断文件是否打开成功:ifs.open("文件路径", 打开方式);
- 读数据:四种读取方式
- 关闭文件:ifs.close();
#include <iostream>
#include <fstream>
using namespace std;
void test()
{
ifstream ifs;
ifs.open("test.txt", ios::in);
if(!ifs.is_open())
exit(1);
char buf0[1024];
string buf2;
char c;
// while(ifs >> buf0) //第一种读文件方式
// cout << buf0 << endl;
// while(ifs.getline(buf0, sizeof(buf0))) //第二种读文件方式
// cout << buf0 << endl;
// while(getline(ifs, buf2)) //第三种读文件方式
// cout << buf2 << endl;
// while((c = ifs.get()) != EOF) //第四种读文件方式 EOF(end of file)结束符
// cout << c;
}
int main()
{
test();
return 0;
}
其中第一,二,三种方式是将文件中的数据一行一行写入字符数组或字符串中,不会行末的换行符。
第四种方式是将数据一个字节一个字节读入,直至读到文件末尾的结束符EOF,第四种读文件方式会读入行末换行符。
二进制文件
以二进制的方式对文件进行读写操作。
打开方式要指定为 ios::binary
写文件
二进制方式写文件主要利用流对象调用成员函数 write
函数原型 ostream& write(const char *buffer, int len);
参数解释:字符指针buffer指向内存中的一段存储空间,len是读写的字节数。
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
class Person //通过二进制文件操作,可以将类写入文件中
{
public:
Person(const char* name, int age)
{
strcpy(m_name, name);
m_age = age;
}
char m_name[64];
int m_age;
};
void test()
{
Person person("张三", 18);
ofstream ofs("test.txt", ios::binary | ios::out);
ofs.write((const char *)&person, sizeof(person));
ofs.close();
}
int main()
{
test();
return 0;
}
ofstream类的成员函数write,有两个参数,const char*要写入数据的内存地址,int len写入数据的类型大小。
对于第一个参数,我们将对象person取地址在强制类型转化为const char*即可。
读文件
二进制方式读文件主要利用流对象调用成员函数read
函数原型:istream& read(char *buffer, int len);
参数解释:字符指针buffer指向内存中一段存储空间,len是读写的字节数。
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
class Person
{
public:
Person()
{
;
}
Person(const char* name, int age)
{
strcpy(m_name, name);
m_age = age;
}
char m_name[64];
int m_age;
};
void test()
{
Person person;
ifstream ifs("test.txt", ios::binary | ios::in);
if(!ifs.is_open())
exit(1);
ifs.read((char *)&person, sizeof(person));
cout << "姓名:" << person.m_name << endl;
cout << "年龄:" << person.m_age << endl;
ifs.close();
}
int main()
{
test();
return 0;
}