_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