• 数据持久化
  • include

  • 文件类型
    • 文本文件:文件以文本的ASCII码形式存储在计算机中
    • 二进制文件:文件以文本的二进制形式存储在计算机中
  • 用于操作文件的三大类
    • ofstream:写操作
    • ifstream:读操作
    • fstream:读写操作

11.1 文本文件

11.1.1 写文件

  • 步骤 ```cpp //包含头文件

    incldue

//创建流对象 ofstream ofs;

//打开文件 ofs.open(“文件路径”,打开方式);

//写数据 ofs<<”写入的数据”;

//关闭文件 ofs.close();

  1. - 文件打开方式(可以用“|”配合使用)
  2. - ios::in — 为读文件而打开文件
  3. - ios::out — 为写文件而打开文件//!!!!!
  4. - ios::ate — 初始位置:文件尾
  5. - ios::app — 追加方式写文件
  6. - ios::trunc — 如果文件存在先删除,再创建
  7. - ios::binary — 二进制方式
  8. - 不指定路径,默认和项目文件路径一致
  9. <a name="kNrfV"></a>
  10. ### 11.1.2 读文件
  11. - 步骤
  12. ```cpp
  13. //包含头文件
  14. #incldue<fstream>
  15. //创建流对象
  16. ifstream ifs;
  17. //打开文件
  18. ifs.open("文件路径",打开方式);
  19. //判断是否打开成功
  20. if(!ifs.is_open()){
  21. cout<<"文件打开失败"<<endl;
  22. return;
  23. }
  24. //逐行读数据(四种方式)
  25. //方法1
  26. char buf[1024] = {0};
  27. while(ifs>>buf)//循环读直到读不到数据
  28. {
  29. cout<<buf<<endl;
  30. }
  31. //方法2
  32. char buf2[1024] = {0};
  33. while(ifs.getline(buf2,sizeof(buf2)))
  34. {
  35. cout<<buf2<<endl;
  36. }
  37. //方法3
  38. string buf3;
  39. while(getline(ifs,buf3))
  40. {
  41. cout<<buf3<<endl;
  42. }
  43. //关闭文件
  44. ifs.close();

11.2 二进制文件

  • 打开方式:ios::binary
  • 操作文件时最好用char[]

    11.2.1 写文件

  • write ```cpp

    include

    class Person { public: char m_Name[64]; int m_Age;

}

void test01 { ofstream ofs; ofs.open(“person.txt”,ios::out | ios::binary);

//另一种写文件方法
ofstream ofs2("person2.txt",ios::out | ios::binary);

Person p = {"张三",18};
ofs.write((const char *)&p, sizeof(Person)); 

ofs.close();

}

<a name="pUlIc"></a>
### 11.2.2 读文件

- read
```cpp
//1、包含头文件
#include<fstream>
class Person
{
public:
    char m_Name[64];
    int m_Age;

}

void test01
{
    //2、创建流对象
    ifstream ofs;
    ifs.open("person.txt",ios::in | ios::binary);

    //3、判断是否打开成功
    if(!ifs.is_open())
    {
        exit(-1);
    }

    //4、读文件
    Person p;
    ifs.read((char *)&p, sizeof(Person)); //注意按创建的类型读出来
    cout<<p.m_Name<<p.m_Age<<endl;

    //5、关闭
    ifs.close();
}