温馨提示×

使用c++ seekg寻找文件位置

c++
小樊
94
2024-07-29 13:33:10
栏目: 编程语言

在C++中,可以使用seekg函数来重新定位输入流的位置。seekg函数有两个参数,第一个参数是要定位的位置,第二个参数是相对于哪个位置进行定位。

下面是一个示例代码,演示如何使用seekg函数来寻找文件位置:

#include <iostream>
#include <fstream>

int main() {
    std::ifstream file("example.txt");

    // 获取当前文件位置
    std::streampos currentPosition = file.tellg();
    std::cout << "Current position: " << currentPosition << std::endl;

    // 移动文件指针到文件末尾
    file.seekg(0, std::ios::end);
    std::streampos endPosition = file.tellg();
    std::cout << "End position: " << endPosition << std::endl;

    // 移动文件指针到文件开头
    file.seekg(0, std::ios::beg);
    std::streampos beginPosition = file.tellg();
    std::cout << "Begin position: " << beginPosition << std::endl;

    file.close();
    return 0;
}

在这个示例中,我们首先打开一个名为example.txt的文件,并获取当前文件位置。然后使用seekg函数将文件指针移动到文件末尾和文件开头,并获取相应的位置。最后关闭文件流。

0