ftell() 返回当前文件位置,也就是说返回FILE指针当前位置。
#include<stdio.h>
long ftell(FILE *stream);
函数 ftell() 用于得到文件位置指针当前位置相对于文件首的偏移字节数。在随机方式存取文件时,由于文件位置频繁的前后移动,程序不容易确定文件的当前位置。使用fseek函数后再调用函数ftell()就能非常容易地确定文件的当前位置。
ftell(fp);利用函数 ftell() 也能方便地知道一个文件的长。如以下语句序列: fseek(fp, 0L,SEEK_END); len =ftell(fp)+1; 首先将文件的当前位置移到文件的末尾,然后调用函数ftell()获得当前位置相对于文件首的位移,该位移值等于文件所含字节数。
DEMO1:
#include <stdio.h>
int main()
{
FILE *stream;
long position;
char list[100];
/* rb+ 读写打开一个二进制文件,允许读数据。*/
if (fopen_s(&stream,"myfile.c","rb+")==0)
{
fread(list,sizeof(char),100,stream);
//get position after read
position=ftell(stream);
printf("Position after trying to read 100 bytes:%ld\n",position);
fclose(stream);
stream=NULL;
}
else
{
fprintf(stdout,"error!\n");
}
system("pause");
return 0;
}
DEMO2:
#include <stdio.h>
#include <process.h>
int main(void)
{
FILE *stream;
stream=fopen("file.txt","w+");
fprintf(stream,"This is a test");
printf("The file pointer is at byte %ld\n",ftell(stream));
system("pause");
return 0;
}
DEMO3:把文件内容打印出来
#include <stdio.h>
int main()
{
FILE *fp=NULL;
int flen=0;
char *p;
/* 以只读方式打开文件*/
if ((fp=fopen("11.txt","rb"))==NULL)
{
printf("\nfile open error\n");
getchar();
getchar();
exit(0);
}
fseek(fp,0L,SEEK_END); //定位到文件末尾
flen=ftell(fp); //得到文件大小
p=(char*)malloc(flen+1); //根据文件大小动态分配内存空间
if (p==NULL)
{
fclose(fp);
return 0;
}
fseek(fp,0L,SEEK_SET); //定义到文件头
fread(p,flen,1,fp); //一次性读取全部文件内容
p[flen]='\0'; //字符串结束标志
printf("%s\n",p);
fclose(fp);
free(p);
system("pause");
return 0;
}
DEMO4:求文件有多少个字节
#include <stdio.h>
int main()
{
FILE *myf;
long f1;
myf=fopen("1.txt","rb");
fseek(myf,0,SEEK_END);
f1=ftell(myf);
fclose(myf);
printf("%d\n",f1);
system("pause");
return 0;
}
DEMO5:通过_filelength来求文件有多少个字节
/*求其文件大小的demo*/
#include <stdio.h>
#include <process.h>
#include <io.h>
int main(void)
{
FILE *pf=NULL;
int file_handle=0;
long file_size=0;
if ((pf=fopen("filelength.c","rb"))==NULL)
{
fprintf(stderr,"File not found");
getchar();
getchar();
return 0;
}
file_handle=_fileno(pf); /*用来取得参数f指定的文件流所使用的文件描述符*/
file_size=_filelength(file_handle); /*/*根据文件描述符取得文件大小*/
printf("文件大小为%ld字节.\n",file_size);
system("pause");
return 0;
}