8.文件操作
//对文件操作要包含头文件<fstream>
//文件分为两种:
// 文本文件-ASCII码
// 二进制文件-二进制形式,一般不能直接读懂
//操作文件的三大类:
// ofstream:写操作
// ifstream:读操作
// fstream:读写操作
//二进制文件 写文件
#include<iostream>
#include<string>
//1.包含头文件
#include<fstream>
using namespace std;
void test01()
{
//2.创建流对象
ofstream ofs;
//3.打开文件
//ofs.open("文件路径", 打开方式);
//ios::in - 为读文件而打开文件
//ios::out - 为写文件而打开
//ios::ate - 初始位置是文件尾
//ios::app - 追加方式写文件
//ios::trunc - 如果文件存在先删除再创建
//ios::binary - 二进制方式
//文件打开方式可以配合使用,利用|运算符
ofs.open("test1.txt", ios::out);
//4.写数据
//ofs << "写入的数据";
ofs << "第一行" << endl << "第二行";
//5.关闭文件
//ofs.close();
ofs.close();
ifstream ifs;
ifs.open("test1.txt", ios::in);
if (!ifs.is_open())
{
cout << "文件打开失败" << endl;
return;
}
//读数据
//方式1
//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
//string buf;
//while (getline(ifs, buf))
//{
// cout << buf<<endl;
//}
//方式4
char c;
while ((c = ifs.get()) != EOF) //EOF - end of file
{
cout << c;
}
ifs.close();
}
class Person
{
public:
char m_Name[64];
int m_Age;
};
void test02()
{
ofstream ofs("person.txt", ios::binary | ios::out);
//ofs.open("person.txt", ios::binary | ios::out);
Person p = { "张三",18 };
ofs.write((const char*)&p, sizeof(Person));
ofs.close();
//二进制文件读文件
ifstream ifs("person.txt", ios::in | ios::binary);
if (!ifs.is_open())
{
cout << "文件打开失败" << endl;
return;
}
Person p1;
ifs.read((char*)&p1, sizeof(Person));
cout << p1.m_Name << endl << p.m_Age << endl;
ifs.close();
}
int main()
{
//test01();
test02();
system("pause");
return 0;
}