C语言文件定位 #
一、fseek函数 #
1.1 函数原型 #
c
int fseek(FILE* fp, long offset, int origin);
1.2 起始位置 #
| 常量 | 说明 |
|---|---|
| SEEK_SET | 文件开头 |
| SEEK_CUR | 当前位置 |
| SEEK_END | 文件末尾 |
1.3 示例 #
c
#include <stdio.h>
int main() {
FILE* fp = fopen("test.txt", "r");
fseek(fp, 0, SEEK_END);
long size = ftell(fp);
printf("文件大小: %ld字节\n", size);
fclose(fp);
return 0;
}
二、ftell函数 #
2.1 函数原型 #
c
long ftell(FILE* fp);
2.2 获取文件大小 #
c
fseek(fp, 0, SEEK_END);
long size = ftell(fp);
三、rewind函数 #
3.1 函数原型 #
c
void rewind(FILE* fp);
3.2 示例 #
c
#include <stdio.h>
int main() {
FILE* fp = fopen("test.txt", "r");
fseek(fp, 10, SEEK_SET);
rewind(fp);
fclose(fp);
return 0;
}
四、总结 #
| 函数 | 功能 |
|---|---|
| fseek | 设置位置 |
| ftell | 获取位置 |
| rewind | 回到开头 |
下一步,让我们学习文件操作实例!
最后更新:2026-03-26