C++ seekp和seekg函数用法

在使用文件流的过程中,涉及到两个函数用来移动读写位置,分别是 seekp 和 seekg,seekp 函数用于已经打开要进行输出的文件,而 seekg 函数则用于已经打开要进行输入的文件。可以将 “p” 理解为 “put”,将 “g” 理解为 “get”,这样理解当然是有根据的,因为 seekp 可用于将信息 put(放入)到文件中,而 seekg 则可用于从文件中 get(获取)信息。
关于seekp()的函数用法如下:
seekp(20L, ios::beg);

ios::beg	从文件头开始计算偏移量
ios::end	从文件末尾开始计算偏移量
ios::cur	从当前位置开始计算偏移量

文件寻找操作:

file.seekp(32L, ios::beg);	将写入位置设置为从文件开头开始的第 33 个字节(字节 32)
file.seekp(-10L, ios::end);	将写入位置设置为从文件末尾开始的第 11 个字节(字节 10)
file.seekp(120L, ios::cur);	将写入位置设置为从当前位置开始的第 121 个字节(字节 120)
file.seekg(2L, ios::beg);	将读取位置设置为从文件开头开始的第 3 个字节(字节 2)
file.seekg(-100L, ios::end);	将读取位置设置为从文件末尾开始的第 101 个字节(字节 100)
file.seekg(40L, ios::cur);	将读取位置设置为从当前位置开始的第 41 个字节(字节 40)
file.seekg(0L, ios:rend);	将读取位置设置为文件末尾

eg:

//This program demonstrates the seekg function.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    // Variable to access file
    char ch;
    // Open the file for reading
    fstream file ("letters.txt", ios::in);
    if (!file)
    {
        cout << "Error opening file.";
        return 0;
    }
    // Get fifth byte from beginning of alphabet file
    file.seekg(5L, ios::beg);
    file.get(ch);
    cout << "Byte 5 from beginning: " << ch << endl;
    // Get tenth byte from end of alphabet file
    file.seekg(-10L, ios::end);
    file.get(ch);
    cout << "Byte 10 from end: " << ch << endl;
    //Go forward three bytes from current position
    file.seekg(3L, ios::cur);
    file.get(ch);
    cout << "Byte 3 from current: " << ch << endl;
    // Close file
    file.close ();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值