操作文件的三大类

  • ofstream:写操作
  • ifstream:读操作
  • fstream:读写操作

文件打开方式

image.png

写文本文件

  1. #include <fstream>
  2. #include <iostream>
  3. using namespace std;
  4. int main()
  5. {
  6. ofstream ofs;
  7. ofs.open("demo.txt", ios::out);//打开文件,并指定打开方式为写文件,如果文件不存在,会自动创建
  8. ofs << "Hello" << endl;//写入内容
  9. ofs << "World" << endl;//写入内容
  10. ofs.close();
  11. return 0;
  12. }

读文本文件

对于文件读取,还是比较推荐方案一二

  • 方案一 ```cpp

    include

    include

    using namespace std;

int main() { ifstream ifs; ifs.open(“demo.txt”, ios::in);//打开文件,并指定打开方式为写文件

  1. if (!ifs.is_open())
  2. {
  3. cout << "文件打开失败!" << endl;
  4. return -1;
  5. }
  6. char buf[1024] = {0};
  7. while (ifs.getline(buf,sizeof(buf)))
  8. {
  9. cout << buf << endl;//打印读取到的内容
  10. }
  11. ifs.close();
  12. return 0;

}

  1. - 方案二
  2. ```cpp
  3. #include <fstream>
  4. #include <iostream>
  5. #include <string>
  6. using namespace std;
  7. int main()
  8. {
  9. ifstream ifs;
  10. ifs.open("demo.txt", ios::in);//打开文件,并指定打开方式为写文件
  11. if (!ifs.is_open())
  12. {
  13. cout << "文件打开失败!" << endl;
  14. return -1;
  15. }
  16. string buf;
  17. while (getline(ifs,buf))
  18. {
  19. cout << buf << endl;//打印读取到的内容
  20. }
  21. ifs.close();
  22. return 0;
  23. }
  • 方案三 ```c

    include

    include

    using namespace std;

int main() { ifstream ifs; ifs.open(“demo.txt”, ios::in);//打开文件,并指定打开方式为写文件

  1. if (!ifs.is_open())
  2. {
  3. cout << "文件打开失败!" << endl;
  4. return -1;
  5. }
  6. char buf[1024] = {0};
  7. while (ifs>>buf)
  8. {
  9. cout << buf << endl;//打印读取到的内容
  10. }
  11. ifs.close();
  12. return 0;

}

  1. - 方案四
  2. ```cpp
  3. #include <fstream>
  4. #include <iostream>
  5. #include <string>
  6. using namespace std;
  7. int main()
  8. {
  9. ifstream ifs;
  10. ifs.open("demo.txt", ios::in);//打开文件,并指定打开方式为写文件
  11. if (!ifs.is_open())
  12. {
  13. cout << "文件打开失败!" << endl;
  14. return -1;
  15. }
  16. char c;
  17. while ((c = ifs.get())!=EOF)//判断是否读到文件尾c
  18. {
  19. cout << c;//打印读取到的内容
  20. }
  21. ifs.close();
  22. return 0;
  23. }

写二进制文件

  1. #include <fstream>
  2. #include <iostream>
  3. using namespace std;
  4. class People{
  5. public:
  6. char mName[128];
  7. int mAge;
  8. };
  9. int main()
  10. {
  11. ofstream ofs("person.txt", ios::out|ios::binary);//打开文件,并指定打开方式为写文件,如果文件不存在,会自动创建
  12. People p = {"小明", 12};
  13. ofs.write((const char *)&p,sizeof(p));
  14. ofs.close();
  15. return 0;
  16. }

读二进制文件

  1. #include <fstream>
  2. #include <iostream>
  3. using namespace std;
  4. class People{
  5. public:
  6. char mName[128];
  7. int mAge;
  8. };
  9. int main()
  10. {
  11. ifstream ifs("person.txt", ios::in|ios::binary);//打开文件,并指定打开方式为写文件,如果文件不存在,会自动创建
  12. if (!ifs.is_open())
  13. {
  14. cout << "文件打开失败!" << endl;
  15. return -1;
  16. }
  17. People p;
  18. ifs.read((char *)&p,sizeof(People));
  19. cout << "姓名:" << p.mName << ",年龄" << p.mAge << endl;
  20. return 0;
  21. }