C++中seekp()和seekg()函数怎么使用

   2025-02-15 8420
核心提示:在C++中,seekp()和seekg()函数用于设置文件指针的位置。seekp()函数用于设置写指针的位置,即用于移动指针到文件中的特定位置以

在C++中,seekp()seekg()函数用于设置文件指针的位置。

seekp()函数用于设置写指针的位置,即用于移动指针到文件中的特定位置以进行写操作。它有两个参数:第一个参数是要移动的偏移量(以字节为单位),第二个参数是指针位置的基准位置。基准位置可以是ios::beg(文件开头)、ios::cur(当前位置)或ios::end(文件末尾)。示例代码如下:

#include <iostream>#include <fstream>using namespace std;int main() {    ofstream file("test.txt", ios::out | ios::binary);    if (!file) {        cout << "Error in creating file!" << endl;        return 0;    }    // 移动写指针到文件末尾    file.seekp(0, ios::end);    // 写入数据    file << "Hello, World!" << endl;    file.close();    return 0;}

seekg()函数用于设置读指针的位置,即用于移动指针到文件中的特定位置以进行读操作。它的使用方法与seekp()函数类似。示例代码如下:

#include <iostream>#include <fstream>using namespace std;int main() {    ifstream file("test.txt", ios::in | ios::binary);    if (!file) {        cout << "Error in opening file!" << endl;        return 0;    }    // 移动读指针到文件开头    file.seekg(0, ios::beg);    // 读取数据    string line;    getline(file, line);    cout << line << endl;    file.close();    return 0;}

在使用seekp()seekg()函数之前,需要先打开文件流,并设置打开模式为ios::in(输入模式)或ios::out(输出模式)。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言