_lseek, _lseeki64

將檔案指標移至指定的位置。

語法

long _lseek(
   int fd,
   long offset,
   int origin
);
__int64 _lseeki64(
   int fd,
   __int64 offset,
   int origin
);

參數

fd
參考已開啟檔案的檔案描述項。

offset
來自 origin 的位元組數目。

origin
初始位置。

傳回值

_lseek 會傳回從檔案開頭到新位置的位移 (以位元組為單位)。 _lseeki64 會傳回以 64 位元整數表示的位移。 函式會傳回 -1L 來指出錯誤。 如果傳遞了不正確參數,例如不正確的檔案描述元,或 的值 origin 無效,或 指定的 offset 位置在檔案開頭之前,則會叫用不正確參數處理常式,如參數驗證 中所述 。 如果允許繼續執行,這些函式會將 errno 設定為 EBADF 並傳回 -1L。 在沒有搜尋功能的裝置上 (例如終端機和印表機),傳回的值未定義。

如需這些錯誤碼和其他錯誤碼的詳細資訊,請參閱 errno_doserrno_sys_errlist_sys_nerr

備註

_lseek 式會將 與 相關聯的 fd 檔案指標移至來自 origin 的新位置。 offset 對檔案的下一項作業會在新位置進行。 自 origin 變數必須是下列其中一個常數,定義于 Stdio.h 中。

origin 描述
SEEK_SET 檔案開頭。
SEEK_CUR 檔案指標的目前位置。
SEEK_END 檔案結尾。

您可以使用 _lseek 將指標重新置放在檔案中的任何位置或檔案結尾之外。

根據預設,此函式的全域狀態會限定于應用程式。 若要變更此行為,請參閱 CRT 中的全域狀態。

需求

常式 必要的標頭
_lseek <io.h>
_lseeki64 <io.h>

如需相容性詳細資訊,請參閱相容性

程式庫

所有版本的 C 執行階段程式庫

範例

// crt_lseek.c
/* This program first opens a file named lseek.txt.
* It then uses _lseek to find the beginning of the file,
* to find the current position in the file, and to find
* the end of the file.
*/

#include <io.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <share.h>

int main( void )
{
   int fh;
   long pos;               /* Position of file pointer */
   char buffer[10];

   _sopen_s( &fh, "crt_lseek.c_input", _O_RDONLY, _SH_DENYNO, 0 );

   /* Seek the beginning of the file: */
   pos = _lseek( fh, 0L, SEEK_SET );
   if( pos == -1L )
      perror( "_lseek to beginning failed" );
   else
      printf( "Position for beginning of file seek = %ld\n", pos );

   /* Move file pointer a little */
    _read( fh, buffer, 10 );

   /* Find current position: */
   pos = _lseek( fh, 0L, SEEK_CUR );
   if( pos == -1L )
      perror( "_lseek to current position failed" );
   else
      printf( "Position for current position seek = %ld\n", pos );

   /* Set the end of the file: */
   pos = _lseek( fh, 0L, SEEK_END );
   if( pos == -1L )
      perror( "_lseek to end failed" );
   else
      printf( "Position for end of file seek = %ld\n", pos );

   _close( fh );
}

輸入︰crt_lseek.c_input

Line one.
Line two.
Line three.
Line four.
Line five.

輸出

Position for beginning of file seek = 0
Position for current position seek = 10
Position for end of file seek = 57

另請參閱

低階 I/O
fseek, _fseeki64
_tell, _telli64