以内存为中心》
std::stringstream; 主要用于类型转换;
std::istream-->std::ifstream; 文件读入内存;
std::ostream-->std::ofstream; 文件从内存写入硬盘文件;
(std::istream,std::ostream)-->std::iostream->std::fstream; 同时支持读写
C++文件读写详解(ofstream,ifstream,fstream)
http://blog.csdn.net/kingstar158/article/details/6859379/
std::stringstream示例:
std::ostream& file_stream
std::stringstream ssm;
HttpPost(url_, arg, ssm);
file_stream << ssm.rdbuf();
ssm<<file_stream .rdbuf();
ssm.seekg(std::ios_base::beg);
读写文件示例:
std::ifstream ifile("D:\\spatialite\\aa.bmp", std::ios_base::in|std::ios_base::binary|std::ios_base::ate);
long size = ifile.tellg();
ifile.seekg(0, std::ios_base::beg);
char* pBuf = new char[size+1];
ifile.read(pBuf, size);
ifile.close();
pBuf[size] = '\0';
char* pBuf2 = new char[size+1];
//std::string strfile = pBuf;文本文件,遇'\0'切割
//strcpy_s(pBuf2, size, pBuf);文本文件,遇'\0'切割
std::string strfile(pBuf,size); //二进制文件必选
memcpy(pBuf2, strfile.c_str(), size);//二进制文件必选
pBuf2[size] = '\0';
{
std::ofstream ofile("D:\\spatialite\\aa2.bmp", std::ios_base::out|std::ios_base::binary);
ofile.write(pBuf2, size);
ofile.close();
}
char *p = pBuf;
trcpy_s(p, str.length()+1, str.c_str());
string::c_str()返回的const char*是包含null结束符的,string::length()返回的长度是不包括null结束符的
//读写文件示例2
#include <fstream>
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
ifstream ifile("", ios_base::in|ios_base::binary|std::ios_base::ate);
long nSize = ifile.tellg();
ifile.seekg(0, std::ios_base::beg);
long nSeg = 1024*1024*2;
long nPos = nSeg;
int nName = 1;
{
int nSmall = 50005;
char* pBuf = new char[nSmall];
ifile.read(pBuf, nSmall);
char sPath[256];
sprintf_s(sPath,"%s%d.reg","",nName);
ofstream ofile(sPath, ios_base::out|ios_base::binary|ios_base::app);
ofile.write(pBuf, nSmall);
ofile.close();
nPos += nSmall;
nName++;
delete[] pBuf;
}
while(nPos <= nSize)
{
char* pBuf = new char[nSeg];
ifile.read(pBuf, nSeg);
char sPath[256];
sprintf_s(sPath,"%s%d.reg","",nName);
ofstream ofile(sPath, ios_base::out|ios_base::binary|ios_base::app);
ofile.write(pBuf, nSeg);
ofile.close();
//if (nPos < nSize)
//ifile.seekg(nPos);
nPos += nSeg;
nName++;
delete[] pBuf;
}
long nRest = nSize-(nPos-nSeg);
if (nRest>0)
{
char* pBuf = new char[nRest];
ifile.read(pBuf, nRest);
char sPath[256];
sprintf_s(sPath,"%s%d.reg","",nName);
ofstream ofile(sPath, ios_base::out|ios_base::binary|ios_base::app);
ofile.write(pBuf, nRest);
ofile.close();
delete[] pBuf;
}
ifile.seekg(0, std::ios_base::beg);
ifile.close();
return 0;
}