C++字符串流操作

以内存为中心》

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值