C ftell: Get File Pointer Position
In C language, you can use the ftell function to get the position of a file pointer. The prototype of the ftell function is as follows:
long int ftell(FILE* stream);
stream is a pointer that points to a file that has already been opened.
The ftell function is used to determine the current position of the file pointer in bytes. If successful, it will return a non-negative value; if an error occurs, it will return -1.
Here is an example code:
#include <stdio.h>
int main() {
FILE* fp = fopen("example.txt", "r");
if (fp == NULL) {
printf("Failed to open the file.\n");
return 1;
}
// 获取文件指针的位置
long int position = ftell(fp);
if (position == -1) {
printf("Failed to get the position of the file pointer.\n");
return 1;
}
printf("The position of the file pointer is %ld.\n", position);
fclose(fp);
return 0;
}
In this example, a file named example.txt is first opened and assigned to the pointer fp. The ftell function is then called to obtain the position of the file pointer, and the return value is stored in the variable position. Finally, the position of the file pointer is printed.
It is important to note that before calling the ftell function, make sure that the file has been successfully opened and the file pointer is valid. The behavior of the ftell function is undefined if the file pointer is invalid.