2012-12-29 19 views
0

我知道一種方法從流讀取和使用它象下面這樣: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); 
    // ... 
} 

但是這個代碼有濫權點,它首先複製從流數據然後通過bufTHIRD_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); 
    // ... 
} 
+4

注意:'while(!s.eof())'是一個反模式。不要這樣做。讀取失敗會將您鎖定爲無限循環。標準模式是:'while(s.read(buf,sizeof(buf))' –

+0

@LokiAstari:謝謝,我會介意你的建議 – deepmax

+1

注意:'strstream'已被棄用,'std :: stringstream'現在是從一個字符串構造的流。 –

回答

0

可以通過先調用其成員方法str得到一個的std :: string一個std :: stringstream的轉換成C風格的字符串,然後調用成員函數的是c_str將其轉換爲一個C樣式的空字符結尾的char []。

1

像這樣的東西可能適合你。

char   buffer[2000]; 
std::istream& s = getStreamReference(); 
s.rdbuf()->pubsetbuf(buffer, 2000); 

while(s) 
{ 
    THIRD_PARTY_FUNCTION(buffer, s.rdbuf()->in_avail()); 
    s.ignore(s.rdbuf()->in_avail()); 

    // Not sure this may go into an infinite loop. 
    // Its late here so I have not tested it. 
} 

注意確定我在意複製2K緩衝區的成本。
分析將不得不表明,這是一個真正的熱點,導致性能顯着下降,然後再考慮進行這種優化。在99%的時間裏,可讀性將成爲我最重要的因素。