扫码加入

  • 正文
  • 相关推荐
申请入驻 产业图谱

飞凌嵌入式ElfBoard-标准IO接口之文件偏移量

2025/11/11
536
加入交流群
扫码加入
获取工程师必备礼包
参与热点资讯讨论

1.fseek

用于设置文件中位置指针的偏移量。

1)头文件

#include <stdio.h>

2)函数原型

int fseek(FILE *stream, long offset, int whence);

3)参数

stream要操作的文件指针。

offset表示以whence为起始点的偏移字节数。

whence:表示offset的起始点位置,可以是以下之一:

SEEK_SET:文件的开头。

SEEK_CUR:当前读写位置。

SEEK_END:文件的末尾。

4)返回值

返回0,表示设置成功;若返回非零值,表示出错。

5)示例:(打开ftest文件,将位置指针移动到文件末尾)

#include <stdio.h>

int main()

{

FILE *fp = fopen("ftest", "r");

if (!fp) {

printf("error: ftest openn");

return -1;

}

if (fseek(fp, 0, SEEK_END)) {

printf("error: ftest fseekn");

fclose(fp);

return -1;

}

printf("succeed: ftest fseekn");

fclose(fp);

return 0;

}

6)编译运行并查看测试结果

succeed: ftest fseek

2.ftell

用于获取文件中位置指针的偏移量。

1)头文件

#include <stdio.h>

2)函数原型

long ftell(FILE*stream);

3)参数

stream:要操作的文件指针。

4)返回值

返回当前文件位置偏移量;若返回-1,表示出错。

5)示例:(打开ftest文件,将位置指针移动到文件末尾,查看当前的文件长度)

#include <stdio.h>

int main()

{

int ft;

FILE *fp = fopen("ftest", "r");

if (!fp) {

printf("error: ftest openn");

return -1;

}

ft = ftell(fp);          //查看当前的文件偏移量

if (ft == -1) {

printf("error: ftest ftell1n");

fclose(fp);

}

printf("ftest ftell1: %dn", ft);

if (fseek(fp, 0, SEEK_END)) {       //将位置指针移动到文件末尾

printf("error: ftest fseekn");

fclose(fp);

}

ft = ftell(fp);           //查看当前的文件偏移量

if (ft == -1) {

printf("error: ftest ftell2n");

fclose(fp);

}

printf("ftest ftell2: %dn", ft);

fclose(fp);

return 0;

}

6)编译运行并查看测试结果

ftest ftell1: 0

ftest ftell2: 15

3.rewind

用于将文件中位置指针设置到文件开头。

1)头文件

#include <stdio.h>

2)函数原型

void rewind(FILE*stream);

3)参数

stream:要操作的文件指针。

4)返回值

无。

5)示例:(打开ftest文件,将位置指针移动到文件末尾,再使用rewind)

#include <stdio.h>

int main()

{

int ft;

FILE *fp = fopen("ftest", "r");

if (!fp) {

printf("error: ftest openn");

return -1;

}

if (fseek(fp, 0, SEEK_END)) {  //将位置指针移动到末尾

printf("error: ftest fseekn");

fclose(fp);

}

ft = ftell(fp);               //查看当前的文件偏移量

if (ft == -1) {

printf("error: ftest ftelln");

fclose(fp);

}

printf("ftest ftell1: %dn", ft);

rewind(fp);                //将位置指针移动到开头

ft = ftell(fp);               //查看当前的文件偏移量

if (ft == -1) {

printf("error: ftest ftelln");

fclose(fp);

}

printf("ftest ftell2: %dn", ft);

fclose(fp);

return 0;

}

6)编译运行并查看测试结果

ftest ftell1: 15

ftest ftell2: 0

相关推荐