19 - ftell()函数

1 函数原型

ftell():获取指定流stream的位置指示器的当前值,函数原型如下:

long int ftell ( FILE * stream );

cstdio库描述如下:

Get current position in stream
1. Returns the current value of the position indicator of the stream.
2. For binary streams, this is the number of bytes from the beginning of the file.
3. For text streams, the numerical value may not be meaningful but can still be used to restore the position to the same position later using fseek.
  1. 流的位置指示器是在流内部维护的一个状态标志:
    (1)用于指示文件读写指针当前所指向的位置,该位置是下一次文件读写操作的起始位置,以偏离文件开头的字节数表示;
    (2)当文件被打开时,文件读写指针会被初始化为指向文件的开头(位置为0)或结尾(附加模式);
    (3)当文件被读写时,文件读写指针会自动更新;
    (4)可以通过ftell(),fseek()和 rewind()等函数来查询和移动文件读写指针。

关于流的位置指示器,cstdio库描述如下:

1. Streams have certain internal indicators that specify their current state and which affect the behavior of some input and output operations performed on them.
2. Position indicator
(1) It is an internal pointer of each stream which points to the next character to be read or written in the next I/O operation. 
(2) Its value can be obtained by the ftell and fgetpos functions, and can be changed using the repositioning functions rewind, fseek and fsetpos.

2 参数

ftell()函数只有一个参数stream:

  1. 参数stream是ftell()函数要查询的流,类型为FILE*;stream主要是文件流,就是fopen()函数的返回值。

cstdio库描述如下:

stream
1. Pointer to a FILE object that identifies the stream.

3 返回值

ftell()函数的返回值类型为long int型:

  1. 获取成功,返回指定流stream的位置指示器的当前值;
  2. 获取失败,则返回-1L,并设置errno以指示错误原因。

cstdioi库描述如下:

1. On success, the current value of the position indicator is returned.
2. On failure, -1L is returned, and errno is set to a system-specific positive value.

4 示例

示例代码如下所示:

int main(void) {
   FILE* fp = NULL;
   char buffer[100] = { 0 };
   char count = 0;
   //
   if ((fp = fopen("1.txt", "rb")) == NULL) {
      perror("Failed to open file ");
      exit(1);
   }
   //
   printf("打开文件\n");
   printf("位置指示器当前值:%ld\n", ftell(fp));
   printf("\n");
   //
   while (fgets(buffer, 100, fp) != NULL) {
      count++;
      printf("第%d行:%s", count, buffer);
      printf("位置指示器当前值:%ld\n", ftell(fp));
      printf("\n");
   }
   //
   fclose(fp);
   //
   return 0;
}

文件内容如下图所示:

在这里插入图片描述

代码运行结果如下图所示:

在这里插入图片描述

代码及运行结果分析如下:

  1. 打开文件后,位置指示器的值为0;
  2. 读完文件第一行后,位置指示器的值为14,"Hello world.“12个字符+”\r\n"2个字符=14个字符;
  3. 读完整个文件后,位置指示器的值为105,说明该文件一共有105个字符,这与查看文件属性显示文件大小为105个字节相符合;
  4. 注意,第8行与第2/4/6行不同;第2/4/6行是空行,是包含r\n两个字符的;第8行仅显示光标位置,并无任何实质性内容。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值