C语言的seekg函数,C++ tellg和tellp函数用法详解

本文通过示例介绍了C++中用于文件随机访问的tellg和tellp函数,它们分别返回读取和写入位置的当前字节编号。程序打开并读取一个名为letters.txt的文件,允许用户输入偏移量来读取不同位置的字符,展示了这两个函数的实际应用。
摘要由CSDN通过智能技术生成

文件流对象有两个可用于随机文件访问的成员函数:tellp 和 tellg。它们的目的是将文件读写位置的当前字节编号作为一个 long 类型整数返回。

如果你了解 seekp 和 seekg 不难猜到,tellp 用于返回写入位置,tellg 则用于返回读取位置。假设 pos 是一个 long 类型的整数,那么以下就是该函数的用法示例:

pos = outFile.tellp();

pos = inFile.tellg();

下面的程序演示了 tellg 函数的用法。它打开了一个名为 letters.txt 文件。文件包含以下字符:

abcdefghijklmnopqrstuvwxyz

//This program demonstrates the tellg function.

#include

#include

#include // For toupper

using namespace std;

int main()

{

// Variables used to read the file

long offset;

char ch;

char response; //User response

// Create the file object and open the file

fstream file("letters.txt", ios::in);

if (!file)

{

cout << "Error opening file.";

return 0;

}

// Work with the file

do {

// Where in the file am I?

cout << "Currently at position " << file.tellg() << endl;

// Get a file offset from the user.

cout << "Enter an offset from the " << "beginning of the file: ";

cin >> offset;

// Read the character at the given offset

file.seekg(offset, ios::beg);

file.get(ch);

cout << "Character read: " << ch << endl;

cout << "Do it again? ";

cin >> response;

} while (toupper(response) == 'Y');

file.close ();

return 0;

}

程序输出结果:

Currently at position 0

Enter an offset from the beginning of the file: 5

Character read: f

Do it again? y

Currently at position 6

Enter an offset from the beginning of the file: 0

Character read: a

Do it again? y

Currently at position 1

Enter an offset from the beginning of the file: 20

Character read: u

Do it again? n

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值