c++中对文件的一些操作

  1. #include <iostream>
  2. #include <iomanip>
  3. #include <fstream>

  4. using namespace std;

  5. int main(){
  6. char buffer[256];
  7. ifstream myfile ("c:\\a.txt");
  8. ofstream outfile("c:\\b.txt");

  9. if(!myfile){
  10.   cout << "Unable to open myfile";
  11.         exit(1); // terminate with error

  12. }
  13. if(!outfile){
  14.     cout << "Unable to open otfile";
  15.         exit(1); // terminate with error

  16. }
  17. int a,b;
  18. int i=0,j=0;
  19. int data[6][2];
  20.   while (! myfile.eof() )
  21.   {
  22.     myfile.getline (buffer,10);
  23.     sscanf(buffer,"%d %d",&a,&b);
  24.     cout<<a<<" "<<b<<endl;
  25.     data[i][0]=a;
  26.     data[i][1]=b;
  27.     i++;
  28.   }
  29. myfile.close();
  30.   for(int k=0;k<i;k++){
  31.      outfile<<data[k][0] <<" "<<data[k][1]<<endl;
  32.      cout<<data[k][0] <<" "<<data[k][1]<<endl;
  33.   }

  34. outfile.close();
  35. return 0;
  36. }
复制代码
无论读写都要包含<fstream>头文件

读:从外部文件中将数据读到程序中来处理

对于程序来说,是从外部读入数据,因此定义输入流,即定义输入流对象:ifsteam infile,infile就是输入流对象。

这个对象当中存放即将从文件读入的数据流。假设有名字为myfile.txt的文件,存有两行数字数据,具体方法:
  1. int a,b;
  2. ifstream infile;
  3. infile.open("myfile.txt");      //注意文件的路径
  4. infile>>a>>b;                   //两行数据可以连续读出到变量里
  5. infile.close()
复制代码
如果是个很大的多行存储的文本型文件可以这么读:
  1. char buf[1024];                //临时保存读取出来的文件内容
  2. string message;
  3. ifstream infile;
  4. infile.open("myfile.js");
  5. if(infile.is_open())          //文件打开成功,说明曾经写入过东西
  6. {
  7. while(infile.good() && !infile.eof())
  8. {
  9.    memset(buf,0,1024);
  10.    infile.getline(buf,1204);
  11.    message = buf;
  12.    ......                     //这里可能对message做一些操作
  13.    cout<<message<<endl;
  14. }
  15. infile.close();
  16. }
复制代码
写:将程序中处理后的数据写到文件当中
对程序来说是将数据写出去,即数据离开程序,因此定义输出流对象ofstream outfile,outfile就是输出流对象,这个对象用来存放将要写到文件当中的数据。具体做法:
  1. ofstream outfile;
  2. outfile.open("myfile.bat");  //myfile.bat是存放数据的文件名
  3. if(outfile.is_open())
  4. {
  5.   outfile<<message<<endl;    //message是程序中处理的数据
  6.   outfile.close();
  7. }
  8. else
  9. {
  10.   cout<<"不能打开文件!"<<endl;
  11. }
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值