1.ftell
long ftell(FILE *stream);
功能:
获得流的偏移量
返回值:
long 类型
fp = fopen("file.txt","r");
ftell(fp);
2.rewind
void rewind(FILE *stream);
功能:
将流的偏移量重新设置到开头、
fp = fopen("file.txt","r");
rewind(fp);
3.fseek
int fseek(FILE *stream, long offset, int whence);
功能:
设置流的偏移量
参数:
stream:文件流指针
offset:偏移量
> 0 向后偏移
< 0 向前偏移
whence:
SEEK_SET 文件开头
SEEK_CUR 文件当前位置
SEEK_END 文件末尾
练习:实操fseek的具体功能
#include<stdio.h>
int main()
{
FILE* fp = NULL;
fp = fopen("file.txt","w");
if(fp == NULL)
{
perror("fail to open file.txt");
return -1;
}
fseek(fp,10,SEEK_SET);
fputc('a',fp); //从开始位置向后偏移10个偏移量,写a
fseek(fp,-5,SEEK_CUR);
fputc('b',fp); //从当前位置向前偏移5个偏移量,写b
fseek(fp,0,SEEK_SET);
fputc('c',fp); //在开始位置处写c
fclose(fp);
return 0;
}
练习:编写一个程序实现统计一个文件的大小
#include<stdio.h>
int main()
{
FILE* fp1 = NULL;
FILE* fp2 = NULL;
long len = 0;
fp1 = fopen("file.txt","r");
if(fp1 == NULL)
{
perror("fail to open file.c");
return -1;
}
fp2 = fopen("file1.txt","w");
if(fp2 == NULL)
{
perror("fail to open file1.c");
return -1;
}
fseek(fp1,0,SEEK_END); //是光标偏移在文件末尾
len = ftell(fp1); //获得流的偏移量
fprintf(fp2,"len = %ld\n",len);
fclose(fp1);
fclose(fp2);
return 0;
}
练习:从终端输入一个单词,获得单词的含义
#include<stdio.h>
#include<string.h>
int main()
{
FILE* fp = NULL; //文件流指针
char tmpbuff[4096] = "abacus n.frame with beads that slide along parallel rods, used for teaching numbers to children, and (in some countries) for counting"; //将dict.txt文件中第一个单词的那一行内容放入数组中
char arr[20] = {0}; //存放要找的单词
char* ptmp = NULL; //分割单词和单词注释的指针
char* p = NULL; //存放fgets的返回值
scanf("%s",arr); //输入要查找的单词
fp = fopen("dict.txt","r");
if(fp == NULL);
{
perror("fail to open dict.txt");
return -1;
}
while(1)
{
p = fgets(tmpbuff,sizeof(tmpbuff),fp); //按流读取,第一次读完后接下来鼠标指向第一次读完的位置,第二次读取从鼠标位置开始,不是从头开始
if(p == NULL)
{
break;
}
ptmp = tmpbuff;
while(*ptmp != ' ' && *ptmp != '\0')
{
ptmp++;
}
*ptmp = '\0'; //分割出单词
ptmp++;
while(*ptmp == ' ') //找单词注释的开头位置,分割出单词注释
{
ptmp++;
}
if(strcmp(arr,tmpbuff) == 0)
{
printf("%s\n",tmpbuff);
printf("%s\n",ptmp);
break;
}
}
printf( "input error\n");
fclose(fp);
return 0;
}