ftell
函式简介
用于得到档案位置指针当前位置相对于档案首的偏移位元组数。
函式名
ftell
函式原型
long ftell(FILE *stream);
函式功能
约束条件
因为ftell返回long型,根据long型的取值範围-231~231-1(-2147483648~2147483647),故对大于2.1G的档案进行操作时出错。
调用示例
ftell(fp);利用函式 ftell() 也能方便地知道一个档案的长。如以下语句序列: fseek(fp, 0L,SEEK_END); len =ftell(fp); 首先将档案的当前位置移到档案的末尾,然后调用函式ftell()获得当前位置相对于档案首的位移,该位移值等于档案所含位元组数。
程式示例
举例1:
#include<stdio.h>intmain(void){FILE*stream;stream=fopen("MYFILE.TXT","w+");fprinTF.htm target=_blank class=infotextkey>TF(stream,"Thisisatest");printf("Thefilepointerisatbyte\%ld\n",ftell(stream));fclose(stream);return0;}
举例2:
#include<stdio.h>#include<stdlib.h>intmain(){FILE*fp;intflen;char*p;/*以唯读方式打开档案*/if((fp=fopen("1.txt","r"))==NULL){printf("\nfileopenerror\n");exit(0);}fseek(fp,0L,SEEK_END);/*定位到档案末尾*/flen=ftell(fp);/*得到档案大小*/p=(char*)malloc(flen+1);/*根据档案大小动态分配记忆体空间*/if(p==NULL){fclose(fp);return0;}fseek(fp,0L,SEEK_SET);/*定位到档案开头*/fread(p,flen,1,fp);/*一次性读取全部档案内容*/p[flen]='\0';/*字元串结束标誌*/printf("%s",p);fclose(fp);free(p);return0;}
程式改进
#include<stdio.h>main(){FILE*myf;longf1;//此处将f1设定为long可以读取更长的档案myf=fopen("1.txt","rb");fseek(myf,0,SEEK_END);f1=ftell(myf);fclose(myf);printf(“%d\n”,f1);}
本文由'兰花又亦'发布,不代表演示站立场,转载/删除联系作者,如需删除请-> 关于侵权处理说明。