C++ streambuf::pubseekpos() 函式



C++ 的 std::streambuf::pubseekpos() 函式用於設定流緩衝區中下一個要讀取或寫入字元的位置。此函式通常用於在流中查詢,從而可以隨機訪問資料的不同部分。

此函式在成功時返回新位置,在失敗時返回 pso_type(-1)。

語法

以下是 std::streambuf::pubseekoff() 函式的語法。

pos_type pubseekpos (pos_type pos, ios_base::openmode which = ios_base::in | ios_base::out);

引數

  • pos &minius; 它指示位置指標的新絕對位置。
  • which - 它通常用於確定將在哪個受控序列上修改位置。

返回值

此函式返回修改後的位置指標的新位置值。

異常

如果丟擲異常,則流緩衝區處於有效狀態。

資料競爭

它修改流緩衝區物件。

示例 1

在下面的示例中,我們將考慮 pubseekpos() 函式的基本用法。

#include <iostream>
#include <sstream>
int main() {
   std::stringbuf a("Welcome");
   a.pubseekpos(10);
   std::cout << a.str().substr(a.pubseekpos(2)) << std::endl;
   return 0;
}

輸出

以下是上述程式碼的輸出 -

lcome

示例 2

考慮以下示例,我們將修改流內容。

#include <iostream>
#include <sstream>
int main() {
   std::stringbuf buffer("XYZDEFG");
   buffer.pubseekpos(0);
   buffer.sputn("ABC", 3);
   std::cout << buffer.str() << std::endl;
   return 0;
}

輸出

上述程式碼的輸出如下 -

ABCDEFG

示例 3

讓我們看下面的示例,我們將重置流的位置。

#include <iostream>
#include <sstream>
int main() {
   std::stringbuf a("ABCDEFGH");
   a.pubseekpos(0);
   std::cout << a.str().substr(a.pubseekpos(6)) << std::endl;
   a.pubseekpos(0);
   std::cout << a.str().substr(a.pubseekpos(0)) << std::endl;
   return 0;
}

輸出

如果我們執行上述程式碼,它將生成以下輸出 -

GH
ABCDEFGH
streambuf.htm
廣告