位置:首页 > 软件操作教程 > 编程开发 > C语言 > 问题详情

C语言 ftell()函数

提问人:刘团圆发布时间:2020-12-03

ftell()函数用来得到流式文件的当前读写位置,其函数原型为:

    long ftell(FILE *fp)

ftell()函数的功能是,返回是当前读写位置偏离文件头部的字节数。若成功,返回当前文件指针位置;若出错,返回-1L。其一般调用形式为:

    ftell(fp);

例如:

    n=ftell(fp);

获取fp指定的文件中,当前读写位置,并将其值传给变量n。

【例题】计算文件长度

算法分析:

①打开文件。

②利用fseek()函数把文件位置指针移到文件末尾。

③使用函数获得此时文件位置指针距离文件开头的字节数,这个字节数就是文件长度。

④输出文件长度,关闭文件。

程序如下:

#include <stdio.h> 

main()

{

    FILE *fp; int f_len; 

    char filename[80];

    printf("Please input the filename:\n"); 

    gets(filename); 

    fp=fopen(fllename,"rb"); 

    fseek(fp,0L,SEEK_END);

    /*从文件末尾移动0个长度,即将文件位置指针指向文件末尾*/ 

    f_len-ftell(fp);      /* 获得文件长度 */

    printf("The length of the file is %d Byte \n",f_len);

    fclose(fp);

}

程序运行时,屏幕显示提示信息:

    Please input the filename:

输入:

    d:\\data.txt /

输出结果为:

    The length of the file is 3 Byte

继续查找其他问题的答案?

相关视频回答
回复(0)
返回顶部