C参考手册
文件输入/输出 | File input/output
ftell
在头文件<stdio.h>中定义 |
|
|
---|---|---|
long ftell( FILE *stream ); |
|
|
返回文件流的文件位置指示符stream
。
如果流以二进制模式打开,则此函数获得的值是从文件开始处的字节数。
如果流在文本模式下打开,则此函数返回的值未指定,仅作为输入来使用fseek()
。
参数
流 |
- |
文件流来检查 |
---|
返回值
文件位置指示器成功或EOF
发生故障时。
出错时,该errno
变量设置为实现定义的正值。
例
与错误检查ftell。
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
/* Prepare an array of f-p values. */
#define SIZE 5
double A[SIZE] = {1.,2.,3.,4.,5.};
/* Write array to a file. */
FILE * fp = fopen("test.bin", "wb");
fwrite(A,sizeof(double),SIZE,fp);
fclose (fp);
/* Read the f-p values into array B. */
double B[SIZE];
fp = fopen("test.bin","rb");
long int pos = ftell(fp); /* position indicator at start of file */
if (pos == -1L)
{
perror("ftell()");
fprintf(stderr,"ftell() failed in file %s at line # %d\n", __FILE__,__LINE__-4);
exit(EXIT_FAILURE);
}
printf("%ld\n", pos);
int ret_code = fread(B,sizeof(double),1,fp); /* read one f-p value */
pos = ftell(fp); /* position indicator after reading one f-p value */
if (pos == -1L)
{
perror("ftell()");
fprintf(stderr,"ftell() failed in file %s at line # %d\n", __FILE__,__LINE__-4);
exit(EXIT_FAILURE);
}
printf("%ld\n", pos);
printf("%.1f\n", B[0]); /* print one f-p value */
return EXIT_SUCCESS;
}
输出:
0
8
1.0
参考
- C11标准(ISO / IEC 9899:2011):
- 7.21.9.4函数(p:337-338)
- C99标准(ISO / IEC 9899:1999):
- 7.19.9.4函数(p:303-304)
- C89 / C90标准(ISO / IEC 9899:1990):
- 4.9.9.4 ftell函数