名稱空間
變體
操作

std::basic_filebuf<CharT,Traits>::seekpos

來自 cppreference.com
< cpp‎ | io‎ | basic filebuf
 
 
 
 
protected:

virtual pos_type seekpos( pos_type sp,

                          std::ios_base::openmode which = std::ios_base::in | std::ios_base::out );

如果可能,將檔案指標重新定位到 sp 指示的位置。如果關聯檔案未開啟 (is_open() == false),則立即失敗。

重新定位執行如下:

1) 如果檔案已開啟用於寫入,則使用 overflow() 寫入 put 區域和當前區域設定所需的任何 unshift 序列。
2) 重新定位檔案指標,如同呼叫 std::fsetpos()
3) 如果檔案已開啟用於讀取,則在必要時更新 get 區域。

如果 sp 不是透過對同一檔案呼叫 seekoff()seekpos() 獲得的,則行為未定義。

目錄

[編輯] 引數

sp - 透過先前對同一檔案呼叫 seekoff()seekpos() 獲得的檔案位置
which - - 定義影響輸入及/或輸出序列的哪個。它可以是下列常量之一或組合
常數 解釋
in 影響輸入序列
out 影響輸出序列

[編輯] 返回值

成功時返回 sp,失敗時返回 pos_type(off_type(-1))

[編輯] 注意

seekpos()std::basic_streambuf::pubseekpos() 呼叫,後者由 std::basic_istream::seekg()std::basic_ostream::seekp() 的單引數版本呼叫。

許多實現不會在 seekpos() 中更新 get 區域,而是委託給由下一個 sgetc() 呼叫的 underflow()

[編輯] 示例

在某些實現中,get 區域由 seekpos() 清空,第二次 underflow() 對於觀察效果是必要的。

#include <fstream>
#include <iostream>
 
struct mybuf : std::filebuf
{
    pos_type seekpos(pos_type sp, std::ios_base::openmode which)
    {
        std::cout << "Before seekpos(" << sp << "), size of the get area is "
                  << egptr() - eback() << " with "
                  << egptr() - gptr() << " read positions available.\n";
 
        pos_type rc = std::filebuf::seekpos(sp, which);
 
        std::cout << "seekpos() returns " << rc << ".\nAfter the call, "
                  << "size of the get area is "
                  << egptr() - eback() << " with "
                  << egptr() - gptr() << " read positions available.\n";
// uncomment if get area is emptied by seekpos()
//        std::filebuf::underflow();
//        std::cout << "after forced underflow(), size of the get area is "
//                  << egptr() - eback() << " with "
//                  << egptr() - gptr() << " read positions available.\n";
 
        return rc;
    }
};
 
int main()
{
    mybuf buf;
    buf.open("test.txt", std::ios_base::in);
    std::istream stream(&buf);
    stream.get(); // read one char to force underflow()
    stream.seekg(2);
}

可能的輸出

Before seekpos(2), size of the get area is 110 with 109 read positions available.
seekpos() returns 2.
After the call, size of the get area is 110 with 108 read positions available.

[編輯] 缺陷報告

下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 55 C++98 seekpos 返回一個未定義值
的非法流位置
pos_type(off_type(-1))
在失敗時返回
LWG 171 C++98 重新定位操作的順序不明確 已明確

[編輯] 另請參閱

呼叫 seekpos()
(std::basic_streambuf<CharT,Traits> 的公共成員函式) [編輯]
[虛擬函式]
使用相對地址重新定位檔案位置
(虛保護成員函式) [編輯]
將檔案位置指示器移動到檔案中特定位置
(函式) [編輯]