溫馨提示×

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

c++
小億
176
2023-11-14 12:28:33
欄目: 編程語言

在C++中,seekp()seekg()函數用于設置文件指針的位置。

seekp()函數用于設置寫指針的位置,即用于移動指針到文件中的特定位置以進行寫操作。它有兩個參數:第一個參數是要移動的偏移量(以字節為單位),第二個參數是指針位置的基準位置?;鶞饰恢每梢允?code>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(輸出模式)。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女