问题遇到的现象和发生背景
关于ftell的偏移到底是如何偏移的问题
问题相关代码,请勿粘贴截图
部分代码引用 https://blog.csdn.net/shulianghan/article/details/121366398
#include <stdio.h>
int main()
{
// 以写文本的方式向文件中写出数据
FILE* p = fopen("D:/number.dat", "w");
// 写出 10 个字符
char array[10] = { 1,2,3,4,5,6,7,8,9,10 };
// 将 10 个字符写出到文件中
fwrite(array, 1, sizeof(array), p);
// 关闭文件
fclose(p);
// 跳过 4 字节读取文件 2 字节
FILE* p2 = fopen("D:/number.dat", "r");
// 使用 ftell 函数获取当前指针位置
int location = ftell(p2);
// 刚打开文件 , 还未读取数据 , 指针指向 0 位置 ★★★
printf("location = %d\n", location);
// 读取数据缓冲区
char array2[2];
// 跳过 4 字节 , 此时当前位置是 0
fseek(p2, 4, SEEK_CUR);
// 使用 ftell 函数获取当前指针位置
location = ftell(p2);
// 跳过了 4 字节数据 , 偏移了 4 字节 ,
// 指针指向第 5 字节 , 索引 4 ★★★
printf("location = %d\n", location);
fseek(p2, 0, SEEK_END);
location = ftell(p2);
printf("location = %d\n", location);
return 0;
}
运行结果及报错内容
我的解答思路和尝试过的方法
我的想法是这样的,文件开始处在第0位置,文件末尾在第11位置,不知道对不对
另外 c primer plus 6th中的这句话也让我很疑惑,这是什么意思,感觉跟我想的有点冲突
我想要达到的结果
1.想要知道一下这个偏移到底是啥意思
2.想要知道我这样想对不对
3.这书上的这句话啥意思
4.
fseek(p2, 0, SEEK_END);
location = ftell(p2);
printf("location = %d\n", location);
这里返回文件末尾到开始的字节数,可这个array只有10个字节,为啥最后出现了11