📜  在C++语言文件处理中使用seekg()设置位置

📅  最后修改于: 2021-05-30 10:41:16             🧑  作者: Mango

seekg()是iostream库(标准库的一部分)中的一个函数,该函数使您可以查找文件中的任意位置。它在文件处理中用于设置要从给定文件的输入流中提取的下一个字符的位置。例如 :

Input : "Hello World" 
Output : World

语法–在文件处理中seekg()有两种语法:

  1. istream&seekg(streampos位置);
  2. istream&seekg(streamoff偏移量,ios_base :: seekdir dir);

描述 –

  • position:是流缓冲区中的新位置。
  • offset:是streamoff类型的整数值,表示流缓冲区中的偏移量。它相对于dir参数。
  • dir:是寻求方向。它是ios_base :: seekdir类型的对象,可以采用以下任何常量值。

我们使用3个方向作为偏移值:

  • ios_base :: beg(从流缓冲区的开头开始的偏移量)。
  • ios_base :: cur(与流缓冲区中当前位置的偏移量)。
  • ios_base :: end(从流缓冲区的末尾偏移)。

代码 –

CPP
// Code to demonstrate the seekg function in file handling
#include 
#include 
 
using namespace std;
  
int main (int argc, char** argv)
{
    // Open a new file for input/output operations
    // discarding any current in the file (assumes
    // a length of zero on opening)
    fstream myFile("test.txt", ios::in | ios::out | ios::trunc);
     
    // Add the characters "Hello World" to the file
    myFile << "Hello World";
     
    // Seek to 6 characters from the beginning of the file
    myFile.seekg(6, ios::beg);
     
    // Read the next 5 characters from the file into a buffer
    char A[6];
    myFile.read(A, 5);
     
    // End the buffer with a null terminating character
    A[5] = 0;
     
    // Output the contents read from the file and close it
    cout << A << endl;
     
    myFile.close();
}


输出 –

World


要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”