fseek()函数的用法及其理解

函数的原型,即使用方法:
int fseek(FILE *stream, long offset, int fromwhere);
功 能: 重定位流上的文件指针
描 述: 函数设置文件指针stream的位置。如果执行成功,stream将指向以fromwhere为基准,偏移offset个字 节的位置。如果执行失败(比如offset超过文件自身大小),则不改变stream指向的位置。
返回值: 成功,返回0,否则返回其他值。

注意:
第一个参数stream为文件指针
第二个参数offset为偏移量,整数表示正向偏移,负数表示负向偏移
第三个参数origin设定从文件的哪里开始偏移,可能取值为:SEEK_CUR、 SEEK_END 或 SEEK_SET
SEEK_SET: 文件开头
SEEK_CUR: 当前位置
SEEK_END: 文件结尾

其中SEEK_SET,SEEK_CUR和SEEK_END和依次为0,1和2.

简言之:
fseek(fp,100L,0);把fp指针移动到离文件开头100字节处;
fseek(fp,100L,1);把fp指针移动到离文件当前位置100字节处;
ffseek(fp,-100L,2);把fp指针退回到离文件结尾100字节处。

函数实验实例

void ModifyFile()
{
    
    
	system("cls");
	Menu1();
	book stu;
	FILE *fp;
	char x[8];

	printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
	printf("请输入图书id:");
	scanf("%s", x);

	fp = fopen("book1.dat", "rb+");

	if (fp == NULL)
	{
    
    
		printf("文件打开失败");
		exit(1);
	}

	fseek(fp, 0, SEEK_SET);
	while (fread(&stu, LEN, 1, fp))
	{
    
    

		if (strcmp(x, stu.id) == 0)
		{
    
    
			printf("请重新输入图书id:   ");
			scanf("%s", stu.id);

			printf("请重新输入书名:    ");
			scanf("%s", stu.name);

			printf("请重新输入书籍作者  : ");
			scanf("%s", &stu.author);

			printf("请重新输入图书出版社  : ");
			scanf("%s", &stu.publish);

			printf("请重新输入图书价格 :   ");
			scanf("%lf", &stu.price);
			printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
			fflush(stdin);
			fseek(fp, 0-LEN, SEEK_CUR);
			fwrite(&stu, LEN, 1, fp);
			fclose(fp);
		}

		if (feof(fp))
		{
    
    
			printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
			printf("没有图书信息");
			printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
		}

	}

	system("pause");
	system("cls");
	return;
}

猜你喜欢

转载自blog.csdn.net/weixin_51871724/article/details/117884241