当前位置:   article > 正文

C++中文件的读写_c++read的头文件

c++read的头文件

一 概念

通过文件,可以将数据持久化。C++中对文件的操作需要包含头文件<fstream>

文本文件:以文本的ASCII码的形式存储在计算机当中。

二进制文件:以二进制的形式存储在计算机中,用户一般无法直接阅读。

操作文本的3个类:ofstream,写操作;ifstream,读操作;fstream,读写操作。

二实践

2.1 文件写入

  1. #include<iostream>
  2. using namespace std;
  3. #include<fstream>
  4. void test() {
  5. ofstream ofs;
  6. ofs.open("test.txt", ios::out);
  7. ofs << "This is a test." << endl;
  8. ofs << "This is a test." << endl;
  9. ofs << "This is a test." << endl;
  10. ofs.close();
  11. }
  12. int main() {
  13. test();
  14. return 0;
  15. }

Note: 文件操作必须包含头文件 fstream;读文件可以利用 ofstream 或 fstream 类;打开文件需要指定操作文件的路径以及打开方式;利用<<可以向文件中写数据;文件操作完毕需要关闭。

2.2 文件读取
读文件步骤:

      1、包含头文件,#include<fstream> ;
      2、创建流对象,ifstream ifs;
      3、打开文件并判断文件是否打开成功,open(“file”,“读取方式”);
      4、读取数据,4中方法进行读取;
      5、关闭文件,ufs.close()。

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. #include<fstream>
  5. void test() {
  6. ifstream ifs;
  7. ifs.open("test.txt", ios::in);
  8. if (!ifs.is_open()) {
  9. cout << "文件打开失败" << endl;
  10. return;
  11. }
  12. /*
  13. char buf[1024] = {0};
  14. // 第一种读取方式
  15. while (ifs >> buf) {
  16. cout << buf << endl;
  17. }*/
  18. // 第二种读取方式
  19. /*
  20. while(ifs.getline(buf, sizeof(buf))) {
  21. cout<<buf<<endl;
  22. }*/
  23. // 第三种读取方式
  24. /*
  25. string buf;
  26. while (getline(ifs, buf)) {
  27. cout << buf << endl;
  28. }*/
  29. // 第四种读取方式
  30. char c;
  31. while ((c = ifs.get()) != EOF) {
  32. cout << c;
  33. }
  34. ifs.close();
  35. }
  36. int main() {
  37. test();
  38. return 0;
  39. }

2.3 二进制写文件

  1. #include<iostream>
  2. using namespace std;
  3. #include<fstream>
  4. class Person {
  5. public:
  6. char m_Name[64];
  7. int m_Age;
  8. };
  9. void test() {
  10. ofstream ofs("person.txt", ios::out | ios::binary);
  11. Person p = { "张三", 20 };
  12. ofs.write((const char*)&p, sizeof(Person));
  13. ofs.close();
  14. }
  15. int main() {
  16. test();
  17. return 0;
  18. }

**Note:**文件输出流对象可以通过write函数,以二进制的方式写数据。

2.4 二进制写文件

  1. #include<iostream>
  2. using namespace std;
  3. #include<fstream>
  4. class Person {
  5. public:
  6. char m_Name[64];
  7. int m_Age;
  8. };
  9. void test() {
  10. ifstream ifs;
  11. ifs.open("person.txt", ios::in | ios::binary);
  12. if (!ifs.is_open()) {
  13. cout << "文件打开失败!" << endl;
  14. return;
  15. }
  16. Person p{};
  17. ifs.read((char*)&p, sizeof(Person));
  18. cout << "姓名:" << p.m_Name << "\n年龄:" << p.m_Age << endl;
  19. ifs.close();
  20. }
  21. int main() {
  22. test();
  23. return 0;
  24. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/690191
推荐阅读
相关标签
  

闽ICP备14008679号