约 2271 字

约 11 分钟

#C 语言标准库函数 fseek

/*********************************************
 * @brief 设置文件位置指示器的值
 * @param fp 文件流
 * @param offset 偏移量
 * @param origin 原点
 * @return 文件流的指针
 ********************************************/
int fseek(FILE* fp, long offset, int origin);

说明

设置文件位置指示器的值。

参数

  • fp - 文件流
  • offset - 相对于原点的偏移量
  • origin - 原点

返回值

  • 成功返回 0
  • 失败返回非 0

#原点

原点说明
SEEK_SET相对文件开头
SEEK_CUR相对当前位置
SEEK_END相对文件末尾

文本模式下(即不含 "b"):

  • 原点 origin 为 SEEK_SET 时,偏移量 offset 只能为零或 ftell 的返回值
  • 原点 origin 为 SEEK_CUR 或 SEEK_END 时,偏移量 offset 只能为零

#示例

#include <stdio.h>

int main(void)
{
    // 打开文件
    FILE* fp = fopen("/tmp/test.txt", "wb+");

    if (fp == NULL)
    {
        perror("文件打开失败");
        return 1;
    }

    printf("当前位置为 %ld\n", ftell(fp));
    fputs("0123456789", fp);    // 写文件
    printf("当前位置为 %ld\n", ftell(fp));

    // 文件位置设为 文件开头 + 3
    fseek(fp, 3, SEEK_SET);
    printf("当前位置为 %ld\n", ftell(fp));

    // 文件位置设为 当前位置 + 5
    fseek(fp, 5, SEEK_CUR);
    printf("当前位置为 %ld\n", ftell(fp));

    // 文件位置设为 当前位置 - 1
    fseek(fp, -1, SEEK_CUR);
    printf("当前位置为 %ld\n", ftell(fp));

    // 文件位置设为 文件末尾 - 4
    fseek(fp, -4, SEEK_END);
    printf("当前位置为 %ld\n", ftell(fp));

    // 关闭文件
    fclose(fp);
    
    return 0;
}

运行结果:

当前位置为 0
当前位置为 10
当前位置为 3
当前位置为 8
当前位置为 7
当前位置为 6

#推荐阅读

#参考标准

  • C23 standard (ISO/IEC 9899:2024):
    • 7.23.9.2 The fseek function (p: TBD)
  • C17 standard (ISO/IEC 9899:2018):
    • 7.21.9.2 The fseek function (p: 245)
  • C11 standard (ISO/IEC 9899:2011):
    • 7.21.9.2 The fseek function (p: 336-337)
  • C99 standard (ISO/IEC 9899:1999):
    • 7.19.9.2 The fseek function (p: 302-303)
  • C89/C90 standard (ISO/IEC 9899:1990):
    • 4.9.9.2 The fseek function

更新: 2025/10/25

作者: PlanC

创建: 2025/8/5