
正文
C++ 读 ,写 文件
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
1 //文件操作
2 //文本文件 读 ,写文件
3
4 #include <iostream>
5 #include <string>
6 #include<fstream>
7
8 using namespace std;
9
10
11 //文本文件 写文件
12 void test01()
13 {
14 //1.包含头文件 fstream
15
16 //2.创建流对象 //写
17 ofstream ofs;
18
19 //3.指定打开方式
20 ofs.open("test.txt", ios::out);
21 //不加地址 默认放在了此项目文件夹里
22
23 //4.写内容
24 ofs << "姓名:zhenglei" << endl;
25 ofs << "性别:男" << endl;
26 ofs << "年龄:21" << endl;
27
28 //5.关闭文件
29 ofs.close();
30
31 }
32 //读文件
33 void test02()
34 {
35 //1.包含头文件
36 //#include<fstream>
37 //2.创建流对象
38
39 ifstream ifs;
40
41 //3.打开文件 并且判断是否打开成功
42 ifs.open("test.txt", ios::in);
43
44 if ( !ifs.is_open())
45 {
46 cout << "文件打开失败!!!" << endl;
47 return;
48 }
49
50 //4.读数据
51 //1种
52 //char buf[1024] = { 0 };
53 //while ( ifs >> buf)
54 //{
55 // cout << buf << endl;
56 //}
57
58 //2种
59 //char buf[1024] = { 0 };
60 //while (ifs.getline(buf, sizeof(buf)))
61 //{
62 // cout << buf << endl;
63 //}
64
65 //3种
66 string buf;
67 while (getline(ifs, buf))
68 {
69 cout << buf << endl;
70 }
71
72
73
74 //4种
75 //char c;
76 //while ((c= ifs.get())!= EOF ) //EOF end of file
77 //{
78 // cout << c;
79 //}
80
81
82
83 //5.关闭文件
84
85 ifs.close();
86 }
87
88
89 int main()
90 {
91 test01();
92
93 test02();
94
95 system("pause");
96
97 return 0;
98
99 }








