我知道一種方法從流讀取和使用它象下面這樣:C++更好的做法是使用流和緩衝區
strstream s; // It can be another standard stream type
// ...
while (!s.eof())
{
char buf[MAX];
s.read(buf, sizeof (buf));
int count = s.gcount();
THIRD_PARTY_FUNCTION(buf, count);
// ...
}
但是這個代碼有濫權點,它首先複製從流數據然後通過buf
到THIRD_PARTY_FUNCTION
。
有沒有什麼辦法可以將代碼改爲像下面的東西(我的意思是下面的代碼避免了額外的副本)?
strstream s; // It can be another standard stream type
// ...
while (!s.eof())
{
char *buf = A_POINTER_TO_DATA_OF_STREAM(s);
int count = AVAIABLE_DATA_SIZE_OF_STREAM(s);
// Maybe it needs s.seekg(...) here
THIRD_PARTY_FUNCTION(buf, count);
// ...
}
注意:'while(!s.eof())'是一個反模式。不要這樣做。讀取失敗會將您鎖定爲無限循環。標準模式是:'while(s.read(buf,sizeof(buf))' –
@LokiAstari:謝謝,我會介意你的建議 – deepmax
注意:'strstream'已被棄用,'std :: stringstream'現在是從一個字符串構造的流。 –