文章目录
简单记录下关于C++的输入流的相关的seekg函数。
一、C++的seekg函数
C++的seekg函数和C语言的seek函数用法差不多,end代表尾部,beg代表头部
c++的 ios 是C++的ios_base标准库的用法
#include <iostream>
#include <fstream>
#include <assert.h>
using namespace std;
int main()
{
ifstream in("./test.txt"); // 通过ifstream 定义输入文件
in.seekg(0, ios::end); // 将光标定义到文件的末尾,偏移值为0
streampos fp = in.tellg(); // tellg函数会返回此时指针的地址(此时光标在末尾)
cout << "文件大小 = " << fp << endl; // 这样就能打印整个文件的大小了
in.seekg(-3, ios::end); // 此时再把光标向前移动3(只有在end的情况下才有负数移动)
streampos fp1 = in.tellg(); // 此时在返回地址
cout << "光标向前偏移3个位置 = " << fp1 << endl;
in.seekg(5);
cout << "此时光光标从第五个字符向后开始读取数据 = " << in.rdbuf(); // rdbuf 从此时光标位置向后开始输出所有的数据
in.seekg(0, ios::beg); // 把光标定义到最开始,偏移为0
cout << in.rdbuf(); //打印整个文件的内容
return 0;
}
^[[Axhh@cluo:~/study/misc$ ./a.out
文件大小 = 13
文件向前偏移 = 16
此时光标 = world!
hello world!
====
d!