2013-04-26 30 views
-1

我在我的程序中有下面的代碼。 IoFile.out只有幾行。爲什麼ostream的put指針被修改,即使我沒有使用ostream對象

int main() 
    { 
    ifstream inFile("Iofile.out", ios::in|ios::out); 
    ostream outStream(inFile.rdbuf()); 

    cout << "tellp outStream " << outStream.tellp() << endl; // tellp outStream 0 
    cout << "tellg inFile " << inFile.tellg() << endl;  // tellg inFile 0 

    cout << inFile.rdbuf(); // Print whole file 

    cout << "tellp outStream " << outStream.tellp() << endl; // tellp outStream 21 
    cout << "tellg inFile " << inFile.tellg() << endl;  // tellg inFile 21 
    return 0;  
} 

tellp和tellg的輸出如註釋中所示。 我的查詢是將文件內容寫入cout時我只希望streambuf的讀指針(即tellg)移動到文件末尾。但在這種情況下,我看到outStream的put指針也移動到文件結尾。爲什麼是這樣 ?爲什麼將文件打印到cout導致outStream的放置指針改變?

+0

你打印整個文件,對吧? 您在ostream構造器中使用了一個streambuffer指針。 – Lefsler 2013-04-26 17:45:03

回答

6

您無法打開ifstream進行書寫。如果要同時讀取&寫權限,請使用fstream

0

您打印整個文件,對吧? 您在ostream構造函數中使用了一個streambuffer指針。 然後你打印數據(這個移動指針)(ostream有一個參考) 並獲取指針位置(在你移動它之後) 你的字符串有多少個字符? (21?) 您在打印rdbuf()時移動了指針。 我認爲它是因爲它裏面的指針使用了一個算術運算

+0

沒有兩個單獨的指針嗎?一個用於讀取,另一個寫入streambuf? – irappa 2013-04-26 17:52:45

+0

ostream是一個指針,但你傳遞一個指針streambuf * sb,並且這兩個streambuf都指向相同的位置 – Lefsler 2013-04-27 18:29:23

相關問題