我是C编程语言的新手。我正在学习文件I/O,对fseek函数感到困惑。这是我的代码
#include <stdio.h>
#include <stdlib.h>
struct threeNumbers {
int n1,n2,n3;
}
int main (){
int n;
struct threeNumbers number;
FILE *filePointer;
if ((filePointer=fopen("\\\\wsl$\\Ubuntu-20.04\\home\\haseeb\\learningC\\file Input and Output\\program2\\program.bin","rb"))==NULL){
printf("error! opening file);
/* if pointer is null, the program will exit */
exit(1);
}
/* moves the cursore at the end of the file*/
fseek(filePointer,-sizeof(struct threeNumbers),SEEK_END);
for(n=1;n<5;++n){
fread(&number,sizeof(struct threeNumbers),1,filePointer);
printf (" n1:%i\tn2:%i\tn3:",number.n1,number.n2,number.n3);
fseek(filePointer,-2*sizeof(struct threeNumbers),SEEK_CUR);
}
fclose(filePointer);
return 0;
}
我知道这个程序会以相反的顺序(从最后到第一)从文件中读取记录并打印出来。我的困惑是我知道“fseek(filePointer,-sizeof(struct三个数字),SEEK_END);”会移动二进制文件末尾的光标。“fseek(filePointer,-2*sizeof(struct三个数字),SEEK_CUR);做什么?我认为它移动到当前位置,但是光标卡明到这个程序中的当前位置的点是什么?还有为什么它是-2而不是仅仅是“-sizeof(struct三个数字)”?
不考虑实际代码,这就是fseek()
所做的:
The fseek() function sets the file position indicator for the stream
pointed to by stream. The new position, measured in bytes, is obtained
by adding offset bytes to the position specified by whence. If whence
is set to SEEK_SET, SEEK_CUR, or SEEK_END, the offset is relative to
the start of the file, the current position indicator, or end-of-file,
respectively. A successful call to the fseek() function clears the
end-of-file indicator for the stream and undoes any effects of the
ungetc(3) function on the same stream.
fseek(filePointer,-sizeof(struct三个数字),SEEK_END)
不会移动二进制文件末尾的光标;它会在文件末尾移动它sizeof(struct三个数字)
。