前言
本篇文章介绍c语言中文件的随机读写
一、文件的随机读写
1.1 fseek()
fseek()函数的作用是根据文件指针的位置和偏移量定位文件指针
int fseek ( FILE * stream, long int offset, int origin );
参数说明
- stream:要定位的文件指针
- offset:偏移量
- orgin
orgin的取值为一个常量
常量 | 位置 |
SEEK_SET | 文件起始位置 |
SEEK_CUR | 文件指针当前位置 |
SEEK_END | 文件末尾 |
#include<stdio.h>
int main()
{
//1. 打开文件
FILE* pf = fopen("data.txt", "r");
if (NULL == pf)
{
perror("fopen()");
return 1;
}
//2.读写文件
//文件数据:20240125 PYSpring 24
//读取一个字符
//将文件指针指到P字符位置
//P的位置相对于起始位置的偏移量为9
fseek(pf,9,SEEK_SET);
int ch = fgetc(pf);
printf("%c\n", ch);
//相对于当前位置的偏移量
//当前指到Y,跳过一个字符,则指到S
fseek(pf,1,SEEK_CUR);
ch = fgetc(pf);
printf("%c\n", ch);
//相对于文件末尾
//offset:-2指到2的位置
fseek(pf,-2,SEEK_END);
ch = fgetc(pf);
printf("%c\n", ch);
//3.关闭文件
fclose(pf);
pf = NULL;
return 0;
}
1.2 ftell()
返回文件指针相对于起始位置的偏移量
long int ftell ( FILE * stream );
ftell()的使用
#include<stdio.h>
int main()
{