传送门
目录
前言
我们来紧接上一篇文章,继续讲解有关c语言文件操作的内容,昨天讲了文件的顺序读写,今天我们来介绍文件的随机读写,文本文件和二进制文件等内容,下面我们就开始吧~
一、文件的随机读写
1.fseek
int fseek ( FILE * stream, long offset, int origin );//根据文件指针的位置和偏移量来定位文件指针。
- offset为偏移量
- origin有三种,分别为:
- SEEK_CUR - 文件指针当前的位置
- SEEK_END - 文件末尾的位置
- SEEK_SET - 文件开始的位置
下面我们来举几个例子,我们已知文件中放的是"abcdef",SEEK_CUR:
#include <stdio.h>
int main()
{
FILE* pf = fopen("test.txt", "r");
if (pf == NULL)
{
perror("fopen");
return 1;
}
int ch = fgetc(pf);//a
printf("%c\n", ch);
ch = fgetc(pf);//b
printf("%c\n", ch);
fseek(pf, 2, SEEK_CUR);//从当前位置向后偏移两位
ch = fgetc(pf);//e
printf("%c\n", ch);
fclose(pf);
pf = NULL;
return 0;
}
SEEK_END:(偏移量必须为负数)
#include <stdio.h>
int main()
{
FILE* pf = fopen("test.txt", "r");
if (pf == NULL)
{
perror("fopen");
return 1;
}
fseek(pf, -1, SEEK_END);//从文件末尾向前偏移一位
int ch = fgetc(pf);//f
printf("%c\n", ch);
fclose(pf);
pf = NULL;
return 0;
}
SEEK_SET:(偏移量必须为正数)
#include <stdio.h>
int main()
{
FILE* pf = fopen("test.txt", "r");
if (pf == NULL)
{
perror("fopen");
return 1;
}
fseek(pf, 2, SEEK_SET);//从文件开始的位置向后偏移两位
int ch = fgetc(pf);//c
printf("%c\n", ch);
fclose(pf);
pf = NULL;
return 0;
}
2.ftell
long int ftell ( FILE * stream );//返回文件指针相对于起始位置的偏移量
我们来举个例子:
#include <stdio.h>
int main()
{
FILE* pf = fopen