面向对象编程自学笔记整理
十二、文件操作
1、文本文件基本操作
#include<fstream>
#include<iostream>
#include<string>
using namespace std;
ofstream ofs;
ifstream ifs;
void test01()
{
ofs.open("test.txt", ios::out);
ofs << "姓名:张三" << endl;
ofs << "性别:男 "<< endl;
ofs << "年龄:18" << endl;
ofs << "姓名:李四" << endl;
ofs << "性别:女" << endl;
ofs << "年龄:12" << endl;
ofs.close();
}
void test02()
{
ifs.open("test.txt", ios::in);
if (!ifs.is_open())
{
cout << "文件打开失败" << endl;
return;
}
char c;
while ((c = ifs.get()) != EOF)
{
cout << c ;
}
ifs.close();
}
int main()
{
test01();
test02();
system("pause");
return 0;
}
2、二进制文件基本操作
#include<iostream>
#include<fstream>
using namespace std;
ofstream ofs;
ifstream ifs;
class person
{
public:
char m_name[64];
int m_age;
};
void test01()
{
ofstream ofs("person.txt", ios::out | ios::binary);
person p = { "张三",19 };
ofs.write((const char*)&p, sizeof(person));
ofs.close();
}
void test02()
{
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 << endl;
ifs.close();
}
int main()
{
test01();
test02();
system("pause");
return 0;
}