当前位置: C语言 -- 标准库 -- <stdio.h> -- ftell

ftell函数


概要:
#include <stdio.h>
long int ftell(FILE *stream);

描述:

该函数获取参数stream指向流的文件位置指示符的当前值。

对于二进制流,文件位置指示符的当前值是距离文件开头的字符数。对于文本流,文件位置指示符包含未指明的信息,fseek函数可使用文件位置指示符将流位置重新定位到ftell函数调用时的位置;两个ftell函数返回值之间的差值不一定有效地表示写入或者读取的字符数。


参数:
FILE *stream

指向打开流的指针。


返回值:

如果调用成功,函数返回文件位置指示符的当前值;如果调用失败,函数返回-1L,并将一个实现定义的正值存入errno。


范例:
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
44 
45 
46 
47 
48 
49 
50 
51 
52 
/*函数ftell范例*/

#include <stdio.h>
#include <stdlib.h>

#define NUMBER 10

int main(void)
{
    FILE *pFile;
    char str[NUMBER+1];
    long int position;
    size_t rBytes;
 
    /*打开文件。*/
    pFile = fopen("gch.bin", "rb");
    if(!pFile)
    {
        perror("Error");
        exit(EXIT_FAILURE);
    }

    /*读取字符。*/
    rBytes = fread(str, sizeof(char), NUMBER, pFile);
    str[rBytes] = '\0';
    
    if(rBytes > 0)
    {
        puts("The characters have been successfully read.");
    }
    else
    {
        puts("Reading characters failed.");
    }

    /*读取字符后,文件位置指示符的当前值。*/
    position = ftell(pFile);
    if(position != -1L)
    {
        printf("Current value of the file position indicator: %ld", position);
    }
    else
    {
        perror("ftell error");
    }
    
    /*关闭文件。*/
    fclose(pFile);

    return 0;
}


结果:

输出读取字符后文件位置指示符的当前值。


相关内容:
fseek 设置流位置的函数。
rewind 将流位置设置为文件开头的函数。


主要参考资料:

1、ISO/IEC 9899:2024

2、ISO/IEC 9899:2018