说明:
1
2
3
4
5
6
|
typedef
QBuffer GBuffer;
class
GMemoryStream :
public
GBuffer
{
...
};
class
std::stringstream :
public
std::iostream{...};
|
1.GMemoryStream转换为std::iostream
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
// 1.定义 QBuffer
QBuffer buff;
buff.open(QBuffer::ReadWrite);
buff.write(
"liujm"
, 5);
// 2.定义 stringstream
std::stringstream strBuff;
// 3.将 QBuffer 写入 stringstream
strBuff.write(buff.buffer().data(), buff.size());
// 测试
char
* arr =
new
char
[buff.size() + 1];
strBuff >> arr;
cout << arr << endl;
// liujm
delete
arr;
|
For example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
void
loadFromStream(std::iostream &io)
{
io.seekg(0, ios::end);
// the ending of a stream
int
nCount = io.tellg();
io.seekg(0, ios::beg);
// the beginning of a stream
char
* arr =
new
char
[nCount + 1];
io.read(arr, nCount);
*(arr + nCount) =
'\0'
;
cout << arr << endl;
delete
arr;
}
void
bufferToIostream()
{
QBuffer buff;
buff.open(QBuffer::ReadWrite);
buff.write(
"liujm"
, 5);
std::stringstream strBuff;
strBuff.write(buff.buffer().data(), buff.size());
loadFromStream(strBuff);
}
|
2.std::iostream转换为GMemoryStream
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
// 1.定义 stringstream
std::stringstream strBuff;
strBuff.write(
"liujm"
, 5);
strBuff <<
'\0'
;
strBuff.write(
"liujm"
, 5);
// 2.定义 QBuffer
QBuffer buff;
buff.open(QIODevice::ReadWrite);
// 3.将 stringstream 中的流写入 QBuffer
buff.write(strBuff.str().c_str(), strBuff.str().size());
// 测试
char
* arr =
new
char
[1 + strBuff.str().size()];
buff.seek(0);
buff.read(arr, strBuff.str().size());
*(arr + strBuff.str().size()) = 0;
cout << arr << endl;
// 注意:此处打印出的结果只有liujm,而不是liujm\0liujm,因为对于c风格的字符串\0就是结尾。QBuffer 流中的数据是 liujm\0liujm
delete
arr;
|
For example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
void
saveToStream(std::iostream &io)
{
// ...
io.write(
"liujm"
, 5);
}
void
iostreamToBuffer()
{
std::stringstream strBuff;
saveToStream(strBuff);
QBuffer buff;
buff.open(QIODevice::ReadWrite);
buff.write(strBuff.str().c_str(), strBuff.str().size());
}
|