文件file.txt中已提前存入内容“sample”
为何用a的方式打开文件
ftell(fp)仍为0?
#include<stdio.h>
#include<stdlib.h>
int main()
{
long position;
FILE *fp;
fp=fopen("D:\\Desktop\\file.txt","a");
position=ftell(fp);
printf("%ld",position);
fclose(fp);
return 0;
}
以附加模式"a"打开文件,只有在写入时指针才会移动到文件尾。程序在打开文件后立即调用了ftell(fp),此时文件指针尚未发生移动,因此返回值为0。
函数 ftell() 用于得到文件位置指针当前位置相对于文件首的偏移字节数。在随机方式存取文件时,由于文件位置频繁的前后移动,程序不容易确定文件的当前位置。使用fseek函数后再调用函数ftell()就能非常容易地确定文件的当前位置。
ftell(fp);利用函数 ftell() 也能方便地知道一个文件的长。如以下语句序列: fseek(fp, 0L,SEEK_END); len =ftell(fp)+1; 首先将文件的当前位置移到文件的末尾,然后调用函数ftell()获得当前位置相对于文件首的位移,该位移值等于文件所含字节数
#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;
}
文件以"a"方式打开时,文件指针指向文件末尾,不是文件开头,因此调用ftell()函数返回的值为0。这是因为,使用"a"方式打开文件时,如果文件不存在,则创建文件,文件指针指向文件末尾;如果文件已存在,则文件指针原本就指向文件末尾。所以要先使用fseek()函数,将指针移动到文件开头。具体做法如下:
#include <stdio.h>
int main()
{
FILE *fp;
long position;
char list[100];
if ((fp = fopen("file.txt", "a+")) != NULL) // 以"a+"方式打开文件
{
fseek(fp, 0, SEEK_SET); // 将文件指针移动到文件开头
fread(list, sizeof(char), 100, fp);
position = ftell(fp);
printf("Position after trying to read 100 bytes: %ld\n", position);
fclose(fp);
fp = NULL;
}
else
{
fprintf(stdout, "error!\n");
}
return 0;
}
其中,fseek()函数的第一个参数是文件指针,第二个参数是偏移量,第三个参数是偏移的起始位置。在本例中,将文件指针移动到文件开头,因此第二个参数为0,第三个参数为SEEK_SET。