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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章