Share via


_lseek、_lseeki64

更新 : 2007 年 11 月

指定された位置にファイル ポインタを移動します。

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 を返します。端末やプリンタなどをシークできないデバイスでは、戻り値は未定義です。

エラー コードの詳細については、「_doserrno、errno、_sys_errlist、および _sys_nerr」を参照してください。

解説

_lseek 関数は、fd に関連付けられているファイル ポインタを origin から offset バイト離れた新しい位置に移動します。ファイルに対する次の操作は、新しい位置で行われます。origin 引数には、Stdio.h で定義されている次のいずれかの定数を指定する必要があります。

  • SEEK_SET
    ファイルの先頭。

  • SEEK_CUR
    ファイル ポインタの現在位置。

  • SEEK_END
    ファイルの終端。

_lseek 関数を使用すると、ファイル内のどこにでもポインタを移動できます。ファイルの終端より後の位置にも移動できます。

必要条件

ルーチン

必須ヘッダー

_lseek

<io.h>

_lseeki64

<io.h>

互換性の詳細については、「C ランタイム ライブラリ」の「互換性」を参照してください。

ライブラリ

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

参照

参照

下位入出力

fseek、_fseeki64

_tell、_telli64