跳到内容

文件定位 ​

读写位置 ​

每次 fgetc/fread/fprintf 之后,文件内部都会记住一个当前位置——下一次读写从这里开始。这个位置像一个光标,随读写自动前进。ftell 返回当前位置(相对文件开头的字节数),rewind 把位置重置到开头:

c
#include <stdio.h>

int main(void)
{
    FILE *fp = fopen("/tmp/cnotes_13_5.txt", "w");
    fputs("hello\n", fp);
    fclose(fp);

    fp = fopen("/tmp/cnotes_13_5.txt", "r");
    int c1 = fgetc(fp);
    printf("读了 '%c',位置=%ld\n", c1, ftell(fp));
    int c2 = fgetc(fp);
    printf("读了 '%c',位置=%ld\n", c2, ftell(fp));
    rewind(fp);
    printf("rewind 后位置=%ld\n", ftell(fp));
    int c3 = fgetc(fp);
    printf("重读 '%c'\n", c3);
    fclose(fp);
    return 0;
}

输出:

text
读了 'h',位置=1
读了 'e',位置=2
rewind 后位置=0
重读 'h'

读第一个字符 h 后位置变成 1,读第二个 e 后变成 2。rewind 把位置拉回 0,再读又是 h。ftell 返回 long,用 %ld 打印。

注:ftell 在二进制模式下返回的是字节数。在文本模式下它的值不一定能直接当字节偏移用(因为换行翻译),但配合 rewind 重置后再读是安全的。

fseek:跳到任意位置 ​

fseek(fp, offset, origin) 把当前位置设到 origin + offset。origin 有三个常量:

宏基准说明
SEEK_SET文件开头offset 为正,从头算
SEEK_CUR当前位置offset 可正可负
SEEK_END文件末尾offset 通常为负,往前算

用 SEEK_SET 可以直接跳到第 N 个元素——这就是随机访问:

c
#include <stdio.h>

int main(void)
{
    int data[] = {100, 200, 300, 400, 500};
    FILE *fp = fopen("/tmp/cnotes_13_5_rand.bin", "wb");
    fwrite(data, sizeof(int), 5, fp);
    fclose(fp);

    fp = fopen("/tmp/cnotes_13_5_rand.bin", "rb");
    fseek(fp, (long)(3 * sizeof(int)), SEEK_SET);
    int val;
    fread(&val, sizeof(int), 1, fp);
    printf("第4个元素=%d\n", val);
    fclose(fp);
    return 0;
}

输出:

text
第4个元素=400

5 个 int 写入后,fseek 跳过前 3 个(偏移 3 * sizeof(int) = 12 字节),直接从第 4 个开始读,得到 400。不用从头读前三个——这就是随机访问的价值。

用 SEEK_END 求文件大小 ​

fseek(fp, 0, SEEK_END) 跳到文件尾,再 ftell 就是文件大小。这是常见的取文件长度手法:

c
#include <stdio.h>

int main(void)
{
    FILE *fp = fopen("/tmp/cnotes_13_5_size.txt", "w");
    fputs("abcdef", fp);
    fclose(fp);

    fp = fopen("/tmp/cnotes_13_5_size.txt", "rb");
    fseek(fp, 0, SEEK_END);
    long size = ftell(fp);
    printf("文件大小=%ld 字节\n", size);
    rewind(fp);
    int ch;
    while ((ch = fgetc(fp)) != EOF) {
        putchar(ch);
    }
    putchar('\n');
    fclose(fp);
    return 0;
}

输出:

text
文件大小=6 字节
abcdef

"abcdef" 共 6 字节。跳到末尾后 ftell 得 6,再 rewind 回开头把内容逐字符打印验证。

注:fseek 返回 0 表示成功,非 0 表示失败(比如试图越过开头)。对 SEEK_END 用正偏移在某些实现上可能扩展文件,不要依赖。求大小用 0 偏移即可。

要点 ​

  • 文件内部维护一个读写位置,随读写自动前进;ftell 返回当前位置,rewind 重置到开头。
  • fseek(fp, offset, origin) 跳到任意位置,origin 为 SEEK_SET/SEEK_CUR/SEEK_END。
  • fseek + SEEK_SET 跳过前面的元素直接读第 N 个,实现随机访问,适合定长记录文件。
  • fseek(fp, 0, SEEK_END) 再 ftell 是求文件长度的惯用法,二进制模式下返回字节数。