文件内部指针
当我们使用函数从文件中读和写数据的时候,文件内部有一个自动往后走的指针,每读一次或写一次它都会往后移动一次,移动的空间和你读取的空间有关。
#include <stdio.h>
void creat_file()
{
FILE *p = fopen("a.dat", "wb");
char temp[10] = {1,2,3,4,5,6,7,8,9,10};
int i;
for(i = 0; i < 10; i++)
{
fwrite(temp, 1, 1, p);
}
fclose(p);
}
void test()
{
FILE *p = fopen("a.txt", "r");
if( p == NULL )
return 0;
char temp[2] = { 0 }
int i;
for(i = 0; i < 2; i++)
{
fread(temp, 1, sizeof(temp), p);
printf("%d, %d", temp[0], temp[1]);
}
fclose(p);
}
通过运行上面的函数可以得到下面结果:
1, 2
3, 4
每次读一次文件内部指针都会自动前进2个字节,这就是文件内部指针,它是自动前进的。
当然我们也可以通过函数来操作它。
Fseek函数
函数作用:
用于操控文件内部指针指向文件内部位置。
函数定义:
int fseek(FILE *p, int n, int _Oriagn)
参数列表:
- p : 目标文件
- n : 内部指针将要移动的位数,正为右,负为左
- _Oriagn : 设定文件内部指针往哪里开始偏移
- SEEK_SET - 文件开头
- SEEK_END - 文件结尾
- SEEK_CUR - 文件中指针当前位置
返回值:
当指针在文件首部,移动位数为负值时,函数会返回-1,如果移动位数为正数,但文件没有足够的空间时,返回的和正常返回的结果一样,都是0。
所以我们不能通过返回值来确定文件指针是否正好指向文件域。
使用示例:
连续两次输出文件前两个字节的数据
void test()
{
FILE *p = fopen("a.dat", "r");
if( p == NULL )
return 0;
char temp[2] = { 0 }
int i;
for(i = 0; i < 2; i++)
{
fseek(p, 0, SEEK_SET);
fread(temp, 1, sizeof(temp), p);
printf("%d, %d", temp[0], temp[1]);
}
fclose(p);
}
其他的使用方法也是这样使用的。
输出结果:
1, 2
1, 2
Ftell函数
函数作用:
用于计算当前文件内部指针位置距文件首地址偏移的字节数量。
函数定义:
long ftell(FILE *P);
参数:
- P : 目标文件
返回值:
返回当前文件内部指针位置距文件首地址的字节大小。
使用方法:
在随机存取的时候,由于文件频繁的前后移动,程序不容易确定当前的位置,我们通常使用该函数来确定当前指针的位置。
void test()
{
FILE *p = fopen("a.dat", "r");
if(p == NULL)
return 0;
char a = 0;
while(!feof(p))
{
fread(&a, 1, 1, p);
int res = ftell(p);
printf("res = %d\n", res);
}
fclose(p);
}
输出结果
res = 0
res = 1
res = 2
res = 3
res = 4
res = 5
res = 6
res = 7
res = 8
res = 10
res = 10
可以看到返回的是文件指针在文件内部的移动状况。
综合应用
生成超大空文件
#include <stdio.h>
void creat_big_file(char *str)
{
FILE *p = fopen(str, "wb");
fseek(p, 999999999, SEEK_END);
char a = 0;
fwrite(&a, 1, 1, p);
fclose(p);
}
void main(int arge, char **arges)
{
if(arge < 2)
return;
creat_big_file(arges[1]);
}
查看文件的大小
#include <stdio.h>
void cat(char *str)
{
FILE *p = fopen(str, "r");
fseek(p, 0, SEEK_END);
printf("%d\n", ftell(p));
}
void main(int arge, char **arges)
{
if(arge < 2)
return ;
cat(arges[1]);
}