在C++中,seekg函數是用于在輸入流中設置讀取位置的。要實現精準定位,你需要傳遞一個偏移量和參考位置作為參數。偏移量表示從參考位置開始的字節數,參考位置可以是std::ios::beg(從文件開始處計算偏移量)、std::ios::cur(從當前位置計算偏移量)或std::ios::end(從文件末尾計算偏移量)。
以下是一個使用seekg實現精準定位的示例:
#include <iostream>
#include <fstream>
int main() {
std::ifstream file("example.txt", std::ios::binary);
if (!file) {
std::cerr << "Error opening file" << std::endl;
return 1;
}
// 將文件指針移動到第5個字節
file.seekg(4, std::ios::beg);
// 檢查文件指針是否成功移動
if (file.fail()) {
std::cerr << "Error seeking file" << std::endl;
return 1;
}
// 讀取當前位置的字符
char ch;
file.get(ch);
std::cout << "Character at position 5: " << ch << std::endl;
// 關閉文件
file.close();
return 0;
}
在這個示例中,我們首先打開一個名為example.txt的文件。然后,我們使用seekg函數將文件指針移動到第5個字節(偏移量為4,參考位置為std::ios::beg)。接下來,我們讀取當前位置的字符并將其輸出到控制臺。最后,我們關閉文件。