[复试机试]c++读取/写入文本文件

读取文件

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <string>
 4 #include <cstdlib>
 5 #include <fstream>
 6 using namespace std;
 7 int main(){
 8     char buffer[256];
 9     ifstream in("test.txt");///文件和代码在同一目录下
10     if(!in.is_open()){
11         cout<<"Error opening file";
12         return 0;
13     }
14     while(!in.eof()){///一行一行的读取
15         in.getline(buffer,100);
16         cout<<buffer<<endl;
17     }
18     return 0;
19 }

写入文件

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <string>
 4 #include <cstdlib>
 5 #include <fstream>
 6 using namespace std;
 7 int main()
 8 {
 9     ///写入文件
10     ofstream out("write.txt");///文件可以不存在,自行创建
11     if(out.is_open())
12     {
13         out<<"opening file
";
14         out<<"12435425324123";
15         out.close();
16     }
17     return 0;
18 }

既可以读,也可以写

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <string>
 4 #include <cstdlib>
 5 #include <fstream>
 6 using namespace std;
 7 int main()
 8 {
 9     ///前提:文件存在才能写入
10     fstream foi("test.txt");
11     if(foi.is_open())
12     {
13         foi<<"YM
";
14         foi<<"abcdefg
";
15         foi.close();
16     }
17     return 0;
18 }
19 int main()
20 {
21     fstream foi("test.txt");///和写入的时候是相同的
22     char buffer[256];
23     if(!foi.is_open()){
24         cout<<"Error opening file";
25         return 0;
26     }
27     while(!foi.eof())
28     {
29         foi.getline(buffer,100);
30         cout<<buffer<<endl;
31     }
32     return 0;
33 }
原文地址:https://www.cnblogs.com/ACMERY/p/6511132.html