C++ Ostream::seekp() 函式



C++ 的 std::ostream::seekp() 函式用於移動流的輸出位置指示器。它允許重新定位流中的寫指標,從而能夠將資料寫入特定位置。此函式可以採用絕對位置或相對於給定位置(開頭、結尾或當前位置)的偏移量。

語法

以下是 std::ostream::seekp() 函式的語法。

ostream& seekp (streampos pos);
or
ostream& seekp (streamoff off, ios_base::seekdir way);

引數

  • pos − 指示流中新的絕對位置。
  • off − 指示偏移量。
  • way − 指示 ios_base::seekdir 型別的物件。

返回值

它返回 ostream 物件 (*this)。

異常

如果丟擲異常,則物件處於有效狀態。

資料競爭

修改流物件,並且對同一流物件的併發訪問可能會導致資料競爭。

示例

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

#include <iostream>
#include <sstream>
int main()
{
    std::ostringstream a;
    a << "W LCOME";
    a.seekp(1);
    a << "E";
    std::cout << a.str() << std::endl;
    return 0;
}

輸出

以上程式碼的輸出如下:

WELCOME

示例

考慮以下示例,我們將使用 seekp() 覆蓋字串的一部分。

#include <iostream>
#include <sstream>
int main()
{
    std::ostringstream a;
    a << "1231114567";
    a.seekp(3);
    a << "XYZ";
    std::cout << a.str() << std::endl;
    return 0;
}

輸出

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

123XYZ4567

示例

讓我們看一下以下示例,我們將把資料追加到末尾。

#include <iostream>
#include <sstream>
int main()
{
    std::ostringstream a;
    a << "Welcone To";
    a.seekp(0, std::ios::end);
    a << " TutorialsPoint";
    std::cout << a.str() << std::endl;
    return 0;
}

輸出

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

Welcone To TutorialsPoint
ostream.htm
廣告