當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C/C++ fseek()用法及代碼示例

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 <stdio.h>
  
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。

相關文章: C語言 fseek() vs rewind()用法及代碼示例

相關用法


注:本文由純淨天空篩選整理自GeeksforGeeks大神的英文原創作品 fseek() in C/C++ with example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。