ifstream是用于读写的C++库。
在C++中,读写是基于指针的。同样,seekg,tellg都和指针有关联。
tellg是告诉指针当前的位置。
seekg是修改指针的位置。
例程1.1:
seekg(地址)
#include#include using namespace std; int main() { ifstream in("in.txt"); string line; streampos pos = in.tellg();//记录当前指针位置 int i = 10; while (i--) {//读到第11行之前 getline(in, line); cout< //读到第11行之前 getline(in, line); cout< 以下是in.txt的内容。
yi er san si wu liu qi ba jiu shi shiyi上文会输出两遍yi到shi,没有shiyi。
例程1.2#include#include using namespace std; int main() { ifstream in("in.txt"); string line; streampos pos = in.tellg();//记录当前指针位置 int i = 10; while (i--) {//读到第11行之前 getline(in, line); cout< //读到第11行之前 getline(in, line); cout< 6) {//读到第11行之前 getline(in, line); cout< 这段代码为扩展代码。在上文的基础之上,第三次会额外输出
an,si,wu,liu。意味着seekg设置到了第8个字节(从0开始是7)的a处。例程2:
seekg(偏移量,基地址)#include#include using namespace std; int main(){ ifstream file; char c,c1,c2,c3,c5; file.open("in.txt"); file.seekg(4); file>>c;//每次>>会输入一个字节。而且,到换行符的时候,指针会自动跳到下一个。 file>>c3; file>>c5; file.seekg(3,ios::beg); file>>c1; file.seekg(-1,ios::end); file>>c2; cout< 上文会输出r,s,a,e,i。
参考1
参考2



