C++ streambuf::pubseekoff() 函式



C++ 的std::streambuf::pubseekoff()函式用於在流中查詢特定位置。它允許重新定位流的內部指標相對於給定偏移量,該偏移量可以指定為絕對位置或相對位置。

如果成功,此函式返回流的新位置;如果發生錯誤,則返回std::streampos(-1)。

語法

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

pos_type pubseekoff (off_type off, ios_base::seekdir way, ios_base::openmode which = ios_base::in | ios_base::out);

引數

  • off − 表示偏移值。
  • way − 表示ios_base::seekdir型別的物件。
  • which − 通常用於確定應修改受控序列中的哪個位置。

返回值

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

異常

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

資料競爭

它修改流緩衝區物件。

示例 1

讓我們來看下面的例子,我們將查詢流的開頭。

#include <iostream>
#include <sstream>
int main() {
   std::stringstream a("WELCOME");
   std::streambuf * b = a.rdbuf();
   b -> pubseekoff(0, std::ios::beg);
   std::cout << static_cast < char > (b -> sgetc()) << std::endl;
   return 0;
}

輸出

以上程式碼的輸出如下:

W

示例 2

考慮下面的例子,我們將把位置從末尾向後移動8個字元,並插入“welcome”。

#include <iostream>
#include <sstream>
int main() {
   std::ostringstream a;
   a.str("Vanakam to TutorialsPoint");
   a.rdbuf() -> pubseekoff(-8, std::ios::end);
   a << "Welcome ";
   std::cout << "Result : " << a.str() << std::endl;
   return 0;
}

輸出

以下是以上程式碼的輸出:

Result : Welcome to TutorialsPoint

示例 3

在下面的例子中,我們將查詢流長度之外的位置,並觀察輸出。

#include <iostream>
#include <sstream>
int main() {
   std::stringstream a("Hi");
   std::streambuf * b = a.rdbuf();
   std::streampos c = b -> pubseekoff(5, std::ios::beg);
   if (c == std::streampos(-1)) {
      std::cout << "Invalid" << std::endl;
   } else {
      std::cout << "Result : " << c << std::endl;
   }
   return 0;
}

輸出

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

Invalid
streambuf.htm
廣告
© . All rights reserved.