c++

C++ fseek 改变读写位置技巧

小樊
92
2024-07-15 17:44:42
栏目: 编程语言

在C++中,可以使用fseek函数来改变文件读写位置,其语法如下:

int fseek(FILE *stream, long offset, int origin);

其中,stream是文件指针,offset是相对于origin的偏移量,origin可以取以下值:

以下是一个示例代码,展示如何使用fseek函数改变文件读写位置:

#include <iostream>
#include <cstdio>

int main() {
    FILE *file = fopen("example.txt", "r");

    if (file) {
        // 移动读写位置到文件末尾
        fseek(file, 0, SEEK_END);

        // 获取当前读写位置
        long pos = ftell(file);
        std::cout << "Current file position: " << pos << std::endl;

        // 移动读写位置到文件开头
        fseek(file, 0, SEEK_SET);

        // 获取当前读写位置
        pos = ftell(file);
        std::cout << "Current file position: " << pos << std::endl;

        fclose(file);
    } else {
        std::cout << "Failed to open file" << std::endl;
    }

    return 0;
}

在上面的示例中,首先打开一个文件并使用fseek函数将读写位置移动到文件末尾,然后获取当前读写位置并输出。接着再将读写位置移动到文件开头,并再次获取当前读写位置并输出。

0
看了该问题的人还看了