tellg和seekg
tellg(), seekg() and seekp() functions are used to set/get the position of get and put pointers in a file while reading and writing.
tellg() , seekg()和seekp()函数用于在读取和写入时设置/获取get和put指针在文件中的位置。
Syntaxes:
语法:
// tellg()
streampos tellg();
// seekg()
istream& seekg (streampos pos);
istream& seekg (streamoff off, ios_base::seekdir way);
// seekp()
stream& seekp (streampos pos);
ostream& seekp (streamoff off, ios_base::seekdir way);
Here,
这里,
pos – represents the new absolute position within the stream (from the beginning).
pos –表示流中新的绝对位置(从头开始)。
off – represents the offset to seek.
off –代表要寻找的偏移量。
pos – represents the following constants,
pos –代表以下常数,
- ios_base::beg / ios::beg – beginning of the stream.
- ios_base :: beg / ios :: beg –流的开始。
- ios_base::cur / ios::cur – current position in the stream.
- ios_base :: cur / ios :: cur –流中的当前位置。
- ios_base::end / ios::end – end the stream.
- ios_base :: end / ios :: end –结束流。
C ++程序来演示tellg(),seekg()和seekp()的示例 (C++ program to demonstrate the example of tellg(), seekg() and seekp())
In the below program, we are using a file 'my.txt', the file contains the following text,
在下面的程序中,我们使用文件“ my.txt”,该文件包含以下文本,
File: my.txt
档案:my.txt
IncludeHelp is specially designed to provide help to students,
working professionals and job seekers
Program:
程序:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream F;
// opening a file in input and output mode
F.open("my.txt", ios::in | ios::out);
// getting current location
cout << F.tellg() << endl;
// seeing 8 bytes/characters
F.seekg(8, ios::beg);
// now, getting the current location
cout << F.tellg() << endl;
// extracting one character from current location
char c = F.get();
// printing the character
cout << c << endl;
// after getting the character,
// getting current location
cout << F.tellg() << endl;
// now, seeking 10 more bytes/characters
F.seekg(10, ios::cur);
// now, getting current location
cout << F.tellg() << endl;
// again, extracing the one character from current location
c = F.get();
// printing the character
cout << c << endl;
// after getting the character,
// getting current location
cout << F.tellg() << endl;
// again, seeking 7 bytes/characters from beginning
F.seekp(7, ios::beg);
// writting a character 'Z' at current location
F.put('Z');
// now, seeking back 7 bytes/characters from the end
F.seekg(-7, ios::end);
// now, printing the current location
cout << "End:" << F.tellg() << endl;
// extracting one character from current location
c = F.get();
// printing the character
cout << c << endl;
// closing the file
F.close();
return 0;
}
Output
输出量
0
8
e
9
19
i
20
End:93
s
After the program execution the file content is,
程序执行后,文件内容为
IncludeZelp is specially designed to provide help to students,
working professionals and job seekers
翻译自: https://www.includehelp.com/cpp-programs/tellg-seekg-and-seekp.example.aspx
tellg和seekg