使用seekg()在 C++ 語言檔案處理中設定位置


seekg() 是 iostream 庫中的一項函式,允許我們在檔案中尋求任意位置。它主要用於設定要從 C++ 檔案處理中的給定檔案所提取的下一個字元的位置。

語法

istream&seekg(streamoff offset, ios_base::seekdir dir);
istream&seekg(streampos position);
Where,
position: It is the new position in the stream buffer.
offset: It is an integer value of type streamoff which represents the offset in the stream’s buffer, relative to the dir parameter.
dir: It is the seeking direction. It is an object of type ios_base::seekdir that can take any offset constant value.

Three direction used for offset values are:
ios_base::beg = from the beginning of the stream’s buffer.
ios_base::cur = from the current position in the stream’s buffer.
ios_base::end = from the end of the stream’s buffer.

所需步驟和操作

Begin
   Open a data file for input/output operations.
   Add ‘TutorialsPoint’ to the file.
   Seek to 9 position from beginning of the file.
   Read the next 5 characters from the file into buffer F.
   End F with null character as terminator character.
   Print the contents.
   Close the file.
End

示例

#include <fstream>
#include <iostream>
using namespace std;
int main (int argc, char** argv) {
   fstream File("d.txt", ios::in | ios::out );
   File << "TutorialsPoint";
   File.seekg(9, ios::beg);
   char F[9];
   File.read(F, 5);
   F[5] = 0;
   cout <<F<< endl;
   File.close();
}

輸出

Point

更新時間:30-Jul-2019

3K+ 瀏覽量

開啟你的職業生涯

完成課程認證

開始
廣告
© . All rights reserved.