C++如何实现读取文件数据

作为C++风格的文件读取方式
可以使用文件流类——fstream类
fstream类有两种子类
分别是用于读出文件的ifstream类
以及用于写入文件ofstream类

在使用是应加入引用 : #include <fstream>
注意该头文件使用std命名空间
还应该加入语句 :using namespace std;

使用的使用应该创建一个文件流对象
比如读入一个文件可以使用下列语句:
      ifstream File;
      char *FileName;
      char DataBuffer[128];
      /* 此处应设定文件名 */
      File.open(FileName);  //打开文件
      //open函数其实有三个参数,此处后两个使用默认值了,具体函数使用请见MSDN
      if(File)
      {  //文件打开成功
         // 此处加入对文件内容的处理
         while(!File.eof())
         {        //循环读入数据
                  File.read(DataBuffer,128);
                  /*对缓冲区中的读入数据进行操作*/
         }
      }
      else
      {  //文件打开失败
         /*进行错误处理*/
      }
      File.close();  //关闭文件
与上述代码类似
将内容写入文件需要创建一个ofstream对象

可以多看看MDSN
可以参考CPP标准函数库 



C++读取文件txt,循环逐行输出
#include <iostream>
            #include <iomanip>
            #include <fstream>
            
            using namespace std;
            
            int main(){
            char buffer[256];
            ifstream myfile ("c:\\a.txt");
            ofstream outfile("c:\\b.txt");
            
            if(!myfile){
              cout << "Unable to open myfile";
                    exit(1); // terminate with error
            
            }
            if(!outfile){
                cout << "Unable to open otfile";
                    exit(1); // terminate with error
            
            }
            int a,b;
            int i=0,j=0;
            int data[6][2];
              while (! myfile.eof() )
              {
                 myfile.getline (buffer,10);
                sscanf(buffer,"%d %d",&a,&b);
                cout<<a<<" "<<b<<endl;
                 data[i][0]=a;
                 data[i][1]=b;
                 i++;
              }
            myfile.close();
              for(int k=0;k<i;k++){
                  outfile<<data[k][0] <<" "<<data[k][1]<<endl;
                 cout<<data[k][0] <<" "<<data[k][1]<<endl;
              }
            
            outfile.close();
             return 0;
            }

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值