#include <stdio.h>
int fseek(FILE *stream, long offset, int whence);
  • 1.
  • 2.

功能:移动文件流(文件光标)的读写位置。

参数:

stream:已经打开的文件指针

offset:根据whence来移动的位移数(偏移量),可以是正数,也可以负数,如果正数,则相对于whence往右移动,如果是负数,则相对于whence往左移动。如果向前移动的字节数超过了文件开头则出错返回,如果向后移动的字节数超过了文件末尾,再次写入时将增大文件尺寸。

whence:其取值如下:

SEEK_SET:从文件开头移动offset个字节

SEEK_CUR:从当前位置移动offset个字节

SEEK_END:从文件末尾移动offset个字节

返回值:

成功:0

失败:-1

#include <stdio.h>
long ftell(FILE *stream);
  • 1.
  • 2.

功能:获取文件流(文件光标)的读写位置。

参数:

stream:已经打开的文件指针

返回值:

成功:当前文件流(文件光标)的读写位置

失败:-1

#include <stdio.h>
void rewind(FILE *stream);
  • 1.
  • 2.

功能:把文件流(文件光标)的读写位置移动到文件开头。

参数:

stream:已经打开的文件指针

返回值:

无返回值

typedef struct Stu
{
	char name[50];
	int id;
}Stu;

//假如已经往文件写入3个结构体
//fwrite(s, sizeof(Stu), 3, fp);
Stu s[3];
Stu tmp; 
int ret = 0;

//文件光标读写位置从开头往右移动2个结构体的位置
fseek(fp, 2 * sizeof(Stu), SEEK_SET);

//读第3个结构体
ret = fread(&tmp, sizeof(Stu), 1, fp);
if (ret == 1)
{
	printf("[tmp]%s, %d\n", tmp.name, tmp.id);
}

//把文件光标移动到文件开头
//fseek(fp, 0, SEEK_SET);
rewind(fp);

ret = fread(s, sizeof(Stu), 3, fp);
printf("ret = %d\n", ret);

int i = 0;
for (i = 0; i < 3; i++)
{
	printf("s === %s, %d\n", s[i].name, s[i].id);
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.