_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位置がファイルの先頭より前の場合、「パラメーターの検証」で説明されているように、無効なパラメーター ハンドラーが呼び出されます。 実行の継続が許可された場合、これらの関数は errnoEBADF に設定し、-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>

互換性の詳細については、「 Compatibility」を参照してください。

ライブラリ

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