2015年1月21日星期三

C++中读写二进制与ASCII混合文本流测试

Read and Write Binary & Text Hybrid Content Stream using C++


The following code snippet is hosted on Github Gist.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
ofstream fout;
int n=31;
double v=9.9998e-79;
string str="Hello,World!";
cout<<"Before"<<endl;
cout<<"n="<<n<<","<<"v="<<v<<endl;
cout<<str<<endl;
fout.open("test.out",ios::binary);
if(!fout.good())
{ cout<<"CANNOT OPEN FILE FOR WRITE!"<<endl; return 1;}
fout.write( (char*)&n ,sizeof(n));
fout.write( (char*)&v ,sizeof(v));
fout.seekp( 1024, ios::beg);
fout<<"Hello,World!"<<endl;
fout.close();
n=38;v=3.14159265354;
str="FAIL";
ifstream fin("test.out",ios::binary);
if(!fin.good())
{ cout<<"CANNOT OPEN FILE FOR READ!"<<endl; return 1;}
fin.read( (char*)&n ,sizeof(n));
fin.read( (char*)&v ,sizeof(v));
cout<<"After"<<endl;
cout<<"n="<<n<<","<<"v="<<v<<endl;
fin.seekg( 1024, ios::beg);
getline(fin,str);
cout<<str<<endl;
fin.close();
system("pause");
return 0;
}
view raw 2013100301.cpp hosted with ❤ by GitHub

1 条评论: