c++输入输出流对象

实验项目名称:输入输出流

一、实验目的

  1. 掌握文本文件和二进制文件的基本访问方法;
  2. 了解一般I/O流和文件流的关系;了解文件与文件流的关系;
  3. 了解文件系统的概念,包括文件指针和关于文件的操作;
  4. 掌握文件类的定义和相关操作的定义、使用方法;
  5. 掌握利用常用函数进行文件的打开、关闭、读写、定位等操作。 

二、实验内容

定义一个Dog类,包括体重和年龄两个数据成员及其成员函数,声明一个实例dog1,体重5,年龄10,使用I/O流把dog1的状态写入磁盘文件。再声明一个实例dog2,通过读取文件dog1的状态赋给dog2。分别用文本方式和二进制方式操作文件。

三、实验代码

文本方式

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 #include <fstream>
 6 
 7 class Dog
 8 
 9 {
10 
11 public:
12 
13     int weight;
14 
15     int age;
16 
17     Dog()
18 
19     {
20 
21          age = 0;
22 
23          weight = 0;
24 
25     }
26 
27 };
28 
29 void main()
30 
31 {
32 
33     Dog dog1;
34 
35     dog1.age = 5;
36 
37     dog1.weight = 10;
38 
39     ofstream ofs;
40 
41     ofs.open("dog1.txt", ios::out);
42 
43     ofs << "年龄:" << dog1.age << endl;
44 
45     ofs << "体重:" << dog1.weight << endl;
46 
47     ofs.close();
48 
49     Dog dog2;
50 
51     ifstream ifs;
52 
53     ifs.open("dog1.txt", ios::in);
54 
55          if (!ifs.is_open())
56          {
57                    cout << "文件打开失败" << endl;
58                    return;
59          }
60 
61  
62 
63     ofs.open("dog2.txt", ios::out);
64 
65     char c;
66 
67     while ((c = ifs.get()) != EOF)
68 
69     {
70 
71          ofs << c;
72 
73     }
74 
75     ifs.close();
76 
77     ofs.close();

 

二进制文件

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 #include <fstream>
 6 
 7 class Dog
 8 
 9 {
10 
11 public:
12 
13     int weight;
14 
15     int age;
16 
17     Dog()
18 
19     {
20 
21          age = 0;
22 
23          weight = 0;
24 
25     }
26 
27 };
28 
29 void main()
30 
31 {
32 
33     Dog dog1;
34 
35     dog1.age = 5;
36 
37     dog1.weight = 10;
38 
39     ofstream ofs;
40 
41     ofs.open("dog1.txt", ios::out|ios::binary);
42 
43     ofs << "年龄:" << dog1.age << endl;
44 
45     ofs << "体重:" << dog1.weight << endl;
46 
47     ofs.close();
48 
49     Dog dog2;
50 
51     ifstream ifs;
52 
53     ifs.open("dog1.txt", ios::in|ios::binary);
54 
55         if (!ifs.is_open())
56          {
57                    cout << "文件打开失败" << endl;
58                    return;
59          }
60 
61  
62 
63     ofs.open("dog2.txt", ios::out|ios::binary);
64 
65     char c;
66 
67     while ((c = ifs.get()) != EOF)
68 
69     {
70 
71          ofs << c;
72 
73     }
74 
75     ifs.close();
76 
77     ofs.close();
78 
79 }
80 
81 }

 

四、测试截图

 

 

 

五、心得体会

(1)写文件用ofstream类,读文件用isftream

(2)读文件时,有多种方式可以读取文件中的内容

①char c;

    while ((c = ifs.get()) != EOF)

    {

         cout << c;

}

②string buf;

while(getline(ifs,buf))

{

cout<<buf<<endl;

}

③char buf[1024]={0};

while(ifs.getline(buf,sizeof(buf)))

{

Cout<<buf<<endl;

}

④char buf[1024]={0};

while(ifs>>buf)

{

Cout<<buf<<endl;

}

posted @ 2023-05-16 17:13  连师傅只会helloword  阅读(24)  评论(0编辑  收藏  举报