[复试机试]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\n";
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\n";
14         foi<<"abcdefg\n";
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

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值