PHP | fseek 函数

怎样移动文件的指针

最近更新时间 2021-01-18 17:48:52

fseek 函数移动文件指针。

fseek() 函数有两个必填参数和一个选填参数。其中第二个参数表示需要移动的字节数。移动的方式由第三个参数决定,默认为文件起始位置。

函数定义

fseek ( resource $handle , int $offset , int $whence = SEEK_SET ) : int
// 源文件位于:ext/standard/file.c
# 函数定义

PHPAPI PHP_FUNCTION(fseek)
{
  zval *res;
  zend_long offset, whence = SEEK_SET;
  php_stream *stream;

  ZEND_PARSE_PARAMETERS_START(2, 3)
    Z_PARAM_RESOURCE(res)
    Z_PARAM_LONG(offset)
    Z_PARAM_OPTIONAL
    Z_PARAM_LONG(whence)
  ZEND_PARSE_PARAMETERS_END();

  PHP_STREAM_TO_ZVAL(stream, res);

  RETURN_LONG(php_stream_seek(stream, offset, (int) whence));
}

参数

  • checkhandle - 文件指针。
  • checkoffset - 移动的字节数。要移动到文件尾之前的位置,需要给 offset 传递一个负值,并设置 whence 为 SEEK_END。
  • checkwhence - 移动的方式。
    • SEEK_SET 从文件的起始位置,设定位置等于 offset 字节。
    • SEEK_CUR 设定位置为当前位置加上 offset。
    • SEEK_END 设定位置为文件尾加上 offset。

返回值

  • checkint - 成功则返回 0;否则返回 -1。注意移动到 EOF 之后的位置不算错误。

示例1: - 使用 fseek() 函数移动文件指针位置。

<?php
/**
 * PHP fseek() 函数移动文件指针位置。
 *
 * @since Version 1.0.0
 * @filesource
 */

// 打开文件
$fileName = 'foo.txt';
$handle = fopen($fileName, 'r');

// 读取文件
$data = fgets($handle, 1024);

// 移动指针到文件开头
// 功能跟 rewind($handle); 一样
fseek($handle, 0);

// 关闭文件
fclose($handle);
rss_feed