C语言文件函数

PHP ftell() 函数 用来获取文件指针相对起始位置的偏移量。

语法

long ftell ( FILE * fp);

参数

  • fp:文件指针。

返回值

返回文件指针相对起始位置的偏移量。

例子

现介绍一个简单的例子了解该函数的使用方法。

在此之前准备文件yxjc123.txt内容

ABC123
例子如下:
#include <stdio.h>
#include<string.h>

int main( )
{

	FILE *file; //定义文件指针
	char c;//读取字符
	long position;//位置
	file = fopen("d:/yxjc123.txt", "r");//打开文件
	if(NULL == file) {
		perror("打开文件失败");
		return -1;
	} 
	
	c=fgetc(file);
	//判断是否到达文件末尾
	while( !feof(file) )
	{  
	  position = ftell(file);
	  printf("读取字符%c,位置%ld\n", c, position);
	  c=fgetc(file);
	} 

       fclose(file); //关闭文件

	getchar();
	return 0;
 
}

输出:

读取字符A,位置1
读取字符B,位置2
读取字符C,位置3
读取字符1,位置4
读取字符2,位置5
读取字符3,位置6