1. 程式人生 > >[C/C++標準庫]_[中級]_[使用stringstream作為記憶體流讀取]

[C/C++標準庫]_[中級]_[使用stringstream作為記憶體流讀取]

場景:

1. C++標準string是可以支援unsigned char* 位元組資料的,只要使用以下兩個函式就可以新增即使是0x0的資料.

string& append( const char* str, size_type num );
string( const char* str, size_type length );

2.stringstream可作為記憶體流來使用,比如再需要處理檔案,過濾內容後再輸出到另一個檔案裡。記憶體流不需要操作檔案指標,比較省時間和io.

流向: ifstream(FILE*)->ostringstream->istringstream->ofstream(FILE*)


測試程式碼: test_stream.cpp

#include <locale>
#include <iostream>
#include <stdlib.h>
#include <string>
#include <fstream>
#include <string.h>
#include <sstream>
using namespace std;

void TestMemoryStream()
{
	unsigned char buf[] = {0xf1,0x0,0xfe,0x00};
	string str((char*)buf,4);
	size_t str_size = str.size();
	cout << "str_size: " << str_size << endl;
	cout << (int)str[1] << endl;

	istringstream iss(str,ios_base::in);
	iss.seekg(0,ios_base::beg);
	char buffer[4];
	memset(buffer,0,sizeof(buffer));
	iss.read(buffer,1);
	cout << (int)(buffer[0] & 0xff) << endl;

	iss.seekg(0,ios_base::end);
	size_t last_pos = iss.tellg();

	cout << "stream size: " << last_pos  << endl;

}

//http://www.cplusplus.com/reference/ios/
int main(int argc, char const *argv[])
{
	//1.測試記憶體流.
	TestMemoryStream();

	//2.檔案流->記憶體流->檔案流.
	//ifstream->ostringstream->istringstream->ofstream
	cout << argv[0] << endl;
	ifstream is(argv[0],ios_base::binary);
	ostringstream oss(ios_base::binary);

	streamsize ss_size = 0;
	char buf[65];
	cout << "begin read is" << endl;
	while(!is.eof())
	{
		is.read(buf,64);
		ss_size = is.gcount();
		if(ss_size)
		{
			oss.write(buf,ss_size);
		}
	}

	cout << "end read is" << endl;
	istringstream iss(oss.str(),ios_base::binary);
	iss.seekg(0,ios_base::beg);

	string str_path(argv[0]);
	str_path.append(".bak");
	ofstream ioo(str_path.c_str(),ios_base::binary);
	
	cout << "start read iss" << endl;
	while(!iss.eof())
	{
		iss.read(buf,64);
		ss_size = iss.gcount();
		if(ss_size)
		{
			ioo.write(buf,ss_size);
		}
	}
	cout << "end read iss" << endl;

	return 0;
}

輸出:

C:\Users\apple\Desktop>test_ifstream.exe
str_size: 4
0
241
stream size: 4
test_ifstream.exe
begin read is
end read is
start read iss
end read iss