1 函数原型
fseek():重新定位指定流stream的文件位置指示符,函数原型如下:
int fseek(FILE *stream, long int offset, int origin);
cstdio库描述如下:
Reposition stream position indicator
1. Sets the position indicator associated with the stream to a new position.
2. For streams open in binary mode, the new position is defined by adding offset to a reference position specified by origin.
3. For streams open in text mode, offset shall either be zero or a value returned by a previous call to ftell, and origin shall necessarily be SEEK_SET.
4. If the function is called with other values for these arguments, support depends on the particular system and library implementation (non-portable).
5. The end-of-file internal indicator of the stream is cleared after a successful call to this function, and all effects from previous calls to ungetc on this stream are dropped.
6. On streams open for update (read+write), a call to fseek allows to switch between reading and writing.
使用 fseek()函数来移动文件内的读写位置,从而可以在文件的任意位置进行读写操作,而不仅仅是文件开头或末尾。
- 对于二进制模式打开的文件,fseek()函数通过向一个参考位置(origin)添加偏移量(offset)来精确地设置文件位置指示符;
- 对于文本模式打开的文件,fseek()函数的使用多有限制:
(1)offset必须为0或ftell()函数的返回值;
(2)origin必须为SEEK_SET,只能从文件开头偏移。
2 参数
fseek()函数有三个参数stream、offset和origin:
- 参数stream是一个指向FILE类型结构的指针;stream指定了fseek()函数要定位的文件流,就是fopen()函数的返回值;
- 参数offset表示相对于origin指定的位置的的偏移量,单位为字节,类型为long int型;offset为正时,向后移动;offset为负时,向前移动;
- 参数origin指定偏移量offset的起始位置,类型为int型。
注意 fseek()函数主要用于定位文件流。
cstdio库描述如下:
stream
1. Pointer to a FILE object that identifies the stream.
offset
1. Binary files: Number of bytes to offset from origin.
2. Text files: Either zero, or a value returned by ftell.
origin
1. Position used as reference for the offset.
origin的3种取值以符号常量的形式定义在cstdio库中:
- SEEK_SET:文件开头;
- SEEK_CUR:当前位置;
- SEEK_END:文件结尾。
3 返回值
fseek()函数的返回值为int型:
- 设置成功,返回0;
- 设置失败,返回非0值。
cstdio库描述如下:
1. If successful, the function returns zero.
2. Otherwise, it returns non-zero value.
4 示例
示例代码如下所示:
int main()
{
//
FILE* fp = NULL;
char buffer[80] = { 0 };
//
fp = fopen("1.txt", "rb");
if (fp == NULL) {
perror("Faile to open file ");
exit(1);
}
//
printf("打开文件\n");
printf("文件位置指示符当前值:%ld\n", ftell(fp));
printf("\n");
//
printf("移动文件位置指示符至文件末尾\n");
fseek(fp, 0, SEEK_END);
printf("文件位置指示符当前值:%ld\n", ftell(fp));
printf("\n");
//
printf("文件大小:%ld\n", ftell(fp));
printf("\n");
//
printf("移动文件位置指示符至文件开头\n");
fseek(fp, 0, SEEK_SET);
printf("文件位置指示符当前值:%ld\n", ftell(fp));
printf("\n");
//
printf("读文件并打印\n");
fgets(buffer, 80, fp);
printf("%s\n", buffer);
printf("文件位置指示符当前值:%ld\n", ftell(fp));
printf("\n");
//
printf("移动文件位置指示符至文件开头\n");
fseek(fp, -ftell(fp), SEEK_END);
printf("文件位置指示符当前值:%ld\n", ftell(fp));
//
printf("\n");
//
fclose(fp);
//
return 0;
}
文件包含内容如下图所示:
代码运行结果如下图所示: