[OPPD] 一次性把整个文件读到std::string

[OPPD] 一次性把整个文件读到std::string

// created by ztwaker on 2006-8-24

// Used for: Read in the whole file

//

 

#include < iostream >

#include < fstream >

#include < string >

 

bool open ( const std :: string & fn , std :: string & data )

{

       std :: ifstream file ( fn . c_str (), std :: ios :: in | std :: ios :: binary );

       if (! file )

              return false ;

      

       file . seekg (0, std :: ios_base :: end );

       long len = file . tellg ();

       file . seekg (0, std :: ios_base :: beg );

      

       char * buffer = new char [ len ];

       file . read ( buffer , len );

       data . assign ( buffer , len );

       delete [] buffer ;

      

       file . close ();

    return true ;

}

 

void test()

{

       using namespace std ;

       const string filename = "Cpp1.ncb" ; //"Cpp22.cpp";

       string s ;

       if ( open ( filename , s ))

              cout << s . size () << endl << s . c_str () << endl ;

}

 

int main()

{

    test();

    return 0;

}

 

/*

OUTPUT:

 

33792

Microsoft C/C++ program database 2.00

.JG

*/

你可能感兴趣的:([OPPD] 一次性把整个文件读到std::string)