PHP | rewind()函数

PHP中的rewind()函数是一个内置函数,用于设置指向文件开头的文件指针的位置。 如果以附加(“a”或“a+”)模式打开文件,无论文件指针的位置如何,写入文件的任何数据都将始终附加。 必须编辑指针的文件作为参数发送给rewind()函数,成功时返回True,失败时返回False。

null

语法:

rewind(file)

使用的参数: PHP中的rewind()函数接受一个参数。

  • 文件 :这是一个强制参数,用于指定要编辑的文件。

返回值: 成功时返回True,失败时返回False。

错误和异常:

  1. 函数的作用是:在出现故障时生成E_警告级别错误。
  2. 要使用rewind()函数,流必须是“可查找的”。
  3. 如果文件以追加模式打开,则写入的数据将被追加,而与指针的位置无关。

例如:

Input: $myfile = fopen("gfg.txt", "r");
        fseek($myfile, "10");
        rewind($myfile);
        fclose($file);

Output: 1

Input : $myfile = fopen("gfg.txt", "r+");
        fwrite($myfile, 'geeksforgeeks');
        rewind($myfile);
        fwrite($myfile, 'portal');
        rewind($myfile);
        echo fread($myfile, filesize("gfg.txt"));
        fclose($myfile);

Output : portalforgeeks
Here all characters of the file as it is after rewind "portal"

下面是演示rewind()函数的程序。

方案1

<?php
$myfile = fopen ( "gfg.txt" , "r" );
// Changing the position of the file pointer
fseek ( $myfile , "10" );
// Setting the file pointer to 0th
// position using rewind() function
rewind ( $myfile );
// closing the file
fclose( $file );
?>


输出:

1

方案2

<?php
$myfile = fopen ( "gfg.txt" , "r+" );
// writing to file
fwrite( $myfile , 'geeksforgeeks a computer science portal' );
// Setting the file pointer to 0th
// position using rewind() function
rewind ( $myfile );
// writing to file on 0th position
fwrite( $myfile , 'geeksportal' );
rewind ( $myfile );
// displaying the contents of the file
echo fread ( $myfile , filesize ( "gfg.txt" ));
fclose( $myfile );
?>


输出:

geeksportalks a computer science portal

参考: http://php.net/manual/en/function.rewind.php

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享