C++ 文件操作

4. 磁盘文件的打开和关闭

     打开

     ofstream outfile;

      if(outfile.open("f1.data",ios::app)==0)    // 打开

            cout<<"打开失败!";

         ……………………

      outfile.close();                                          //关闭 

  

   

5. 文件写入

#include <fstream>
#include <iostream>

#include <string>        //一定不能少了,否则报错 error C2679
using namespace std;

int main()

{
   string str;
   ofstream out("d.txt",ios::out);       //等价于ofstream out("d.txt")   

   if(!out)              //若打开失败,out返回0值

  {

      cerr<<"打开失败!"<<endl;

      exit(0);

   }
   str="床前明月光/n疑是地上霜/n举头望明月/n低头思故乡/n";
   out<<str<<endl;
   return 0;  
}


6. 读文件到控制台

#include <fstream>
#include <iostream>
#include<string>
using namespace std;
int main()

{
    ifstream infile("d://new//d.txt",ios::in); //定义输入文件的流对象,以输入方式打开磁盘文件d.txt,第二个参数可去
   if(!infile)
    {
        cerr<<"打开失败!"<<endl;
        exit(1);
    }
   for(string str;getline(infile,str);)  //逐行打开并逐行显示,因此在循环中实现
     cout<<str<<"/n";
     infile.close();
  return 0;   
}

      或把    for(string str;getline(in,str);)
                cout<<str<<"/n";

 两句改为   string str;
                while(getline(in,str))
                       cout<<str<<"/n";

7. 文件复制

#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
  ifstream in("d.txt");
  if(!in)
  {
     cerr<<"打开源文件失败!"<<endl;
     exit(1);
  }
  ofstream out("b.txt");
  if(!out)
  {
     cerr<<"打开目的文件失败!"<<endl;
     exit(1);
  }
  for(string str;getline(in,str);)
  out<<str<<endl;                   //注意是out
  cout<<"文件复制成功!"<<endl;

  in.close();

  out.close();
  return 0;   
}


本文来自优快云博客,转载请标明出处:http://blog.youkuaiyun.com/Deutschester/archive/2009/06/24/4295723.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值