栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

ifstream.seekg、ifstream.tellg的用法

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ifstream.seekg、ifstream.tellg的用法

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/951545.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号