c++之文件操作,(不以简单而不为,不以难而畏为)

本文提供了两个简单的C++示例程序,分别演示如何进行文件写入和读取操作。通过使用标准库中的`fstream`,展示了基本的文件操作流程,包括打开文件、写入数据、读取数据及关闭文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

操作相对简单,但不要以为简单而不动手,文件操作流在Java和C++都很重要,以下是雏形:(让您溅笑了)

文件写入操作

#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main(){
 ofstream file("c:\\hello.txt");
 if(!file){
  cout<<"can't open it"<<endl;
  return -1;
 }
 string s="hello";
 for(int i=0;i<10;++i){
  file<<"hello ";
 }
 file<<endl;

 file.close();
    system("pause");
 return 0;
}

文件输出操作:

#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main(){
 ifstream infile("c:\\world.txt");
 if(!infile){
  cout<<"can't open it"<<endl;
  return -1;
 }
 string s;
 while(getline(infile,s)){
  cout<<s<<endl;
 }

  infile.close();
 system("pause");
 return 0;
}

也可以用流迭代器来完成,欢迎看我的《IO流迭代器》,里面有讲解很清楚

不以易而不为,不以难而畏为!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值