📜  C / C++中的fseek()示例

📅  最后修改于: 2021-05-26 03:07:12             🧑  作者: Mango

fseek()用于将与给定文件关联的文件指针移动到特定位置。
句法:

int fseek(FILE *pointer, long int offset, int position)
pointer: pointer to a FILE object that identifies the stream.
offset: number of bytes to offset from position
position: position from where offset is added.

returns:
zero if successful, or else it returns a non-zero value 

position定义了文件指针需要相对于其移动的点。它具有三个值:
SEEK_END:它表示文件的结尾。
SEEK_SET:它表示文件的开始。
SEEK_CUR:表示文件指针的当前位置。

// C Program to demonstrate the use of fseek()
#include 
  
int main()
{
    FILE *fp;
    fp = fopen("test.txt", "r");
      
    // Moving pointer to end
    fseek(fp, 0, SEEK_END);
      
    // Printing position of pointer
    printf("%ld", ftell(fp));
  
    return 0;
}

输出:

81

解释

文件test.txt包含以下文本:

"Someone over there is calling you.
we are going for work.
take care of yourself."

当我们实现fseek()时,我们将指针相对于文件末尾移动了0距离,即,指针现在指向文件末尾。因此输出为81。

相关文章: fseek vs倒带C

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。