位置:首頁 > 軟件操作教程 > 編程開發(fā) > C語言 > 問題詳情

C語言 ftell()函數(shù)

提問人:劉團圓發(fā)布時間:2020-12-03

ftell()函數(shù)用來得到流式文件的當前讀寫位置,其函數(shù)原型為:

    long ftell(FILE *fp)

ftell()函數(shù)的功能是,返回是當前讀寫位置偏離文件頭部的字節(jié)數(shù)。若成功,返回當前文件指針位置;若出錯,返回-1L。其一般調(diào)用形式為:

    ftell(fp);

例如:

    n=ftell(fp);

獲取fp指定的文件中,當前讀寫位置,并將其值傳給變量n。

【例題】計算文件長度

算法分析:

①打開文件。

②利用fseek()函數(shù)把文件位置指針移到文件末尾。

③使用函數(shù)獲得此時文件位置指針距離文件開頭的字節(jié)數(shù),這個字節(jié)數(shù)就是文件長度。

④輸出文件長度,關閉文件。

程序如下:

#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 /

輸出結(jié)果為:

    The length of the file is 3 Byte

繼續(xù)查找其他問題的答案?

相關視頻回答
回復(0)
返回頂部