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

来源:互联网 发布:淘宝 澳洲 安卓 编辑:程序博客网 时间:2024/05/25 12:21
作为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;            }

原创粉丝点击