C语言fseek函数

C语言fseek函数教程

C 语言 中,我们写入 文件 或者读取文件之后,文件 指针 默认会移动到文件的末尾,此时如果我们再次需要读取文件,那么我们是无法正确读取到文件内容的。

C 语言给我们提供了 fseek 函数,用来实现任意的移动文件指针,注意与 rewind 函数的区别,rewind 函数只能将文件指针移动到文件的开始。

C语言fseek函数详解

语法

int fseek(FILE *fp, long offset, int origin);

参数

参数 描述
fp 文件指针。
offset 偏移量,也就是要移动的字节数。offset 为正时,向后移动;offset 为负时,向前移动。
origin origin 为起始位置,也就是从何处开始计算偏移量。

origin参数

起始点 常量名 常量值
文件开头 SEEK_SET 0
当前位置 SEEK_CUR 1
文件末尾 SEEK_END 2

头文件

fseek 函数在 stdio.h 的头文件里面。

案例

使用fseek文件指针移动到开始

使用 fseek 函数,实现将文件指针移动到文件的开始

#include <stdio.h> #include <stdlib.h> int main() { printf("嗨客网(www.haicoder.net)\n\n"); FILE *fp = NULL; char str[100]; if ( (fp = fopen("c:\\1.txt", "wt+")) == NULL ) { puts("Open file failed\n"); return; } fputs("Hello HaiCoder\n", fp); fputs("Hello C\n", fp); puts("Write file success\n"); while (fgets(str, 100, fp) != NULL) { printf("Read line = %s", str); } fclose(fp); return 0; }

程序运行后,控制台输出如下:

23_c语言fseek函数移动文件指针.png

我们首先,使用了 fopen 函数打开了文件,接着,我们使用了 fputs 函数将 字符串 内容写入到文件中,最后,我们使用了 while 循环 加上 fgets 函数读取文件。

此时,我们看到,我们并没有读取到任何文件内容,这是因为,我们写入文件内容之后,文件指针已经移动到了文件末尾,因此,无法正确读取文件内容,现在,我们修改程序如下:

#include <stdio.h> #include <stdlib.h> int main() { printf("嗨客网(www.haicoder.net)\n\n"); FILE *fp = NULL; char str[100]; if ( (fp = fopen("c:\\1.txt", "wt+")) == NULL ) { puts("Open file failed\n"); return; } fputs("Hello HaiCoder\n", fp); fputs("Hello C\n", fp); puts("Write file success\n"); fseek(fp, 0, SEEK_SET); while (fgets(str, 100, fp) != NULL) { printf("Read line = %s", str); } fclose(fp); return 0; }

程序运行后,控制台输出如下:

24_c语言fseek函数移动文件指针.png

这次,我们在写入文件之后,使用了 fseek 函数,将文件指针再次移动到文件的开始,此时再次读取文件内容,我们发现,已经可以读取到文件内容了。

我们再次,使用 feek 函数,实现将文件指针移动到文件的 10 个字节开始的位置,修改代码如下:

#include <stdio.h>
#include <stdlib.h>
int main() 
{
	printf("嗨客网(www.haicoder.net)\n\n");
	FILE *fp = NULL;
	char str[100];
	if ( (fp = fopen("c:\\1.txt", "wt+")) == NULL )
	{
		puts("Open file failed\n");
        return;
	}
	fputs("Hello HaiCoder\n", fp);
	fputs("Hello C\n", fp);
	puts("Write file success\n");
	fseek(fp, 10, SEEK_SET);
	while (fgets(str, 100, fp) != NULL)
	{
		printf("Read line = %s", str);
	}
	fclose(fp);
	return 0;
}

程序运行后,控制台输出如下:

25_c语言fseek函数移动文件指针.png

这次,我们在写入文件之后,使用了 fseek 函数,将文件指针移动到文件的开始 10 个字节的位置,此时再次读取文件内容,我们发现,读取的第一行文件的内容已经不全了。

C语言fseek函数总结

C 语言给我们提供了 fseek 函数,用来实现任意的移动文件指针,注意与 rewind 函数的区别,rewind 函数只能将文件指针移动到文件的开始。