百科狗-知识改变命运!
--

fseek() - 在文件指针中定位 - php 文件目录函数

是丫丫呀1年前 (2023-11-21)阅读数 19#技术干货
文章标签位置

fseek()

(PHP 4, PHP 5, PHP 7)

在文件指针中定位

说明

fseek(resource $handle,int $offset[,int $whence= SEEK_SET]): int

在与$handle关联的文件中设定文件指针位置。新位置从文件头开始以字节数度量,是以$whence指定的位置加上$offset。

In general, it is allowed to seek past the end-of-file; if data is then written, reads in any unwritten region between the end-of-file and the sought position will yield bytes with value 0. However, certain streams may not support this behavior, especially when they have an underlying fixed size storage.

参数

$handle

fseek() - 在文件指针中定位 - php 文件目录函数

文件系统指针,是典型地由fopen()创建的resource(资源)。

$offset

偏移量。

要移动到文件尾之前的位置,需要给$offset传递一个负值,并设置$whence为SEEK_END

$whence

$whencevalues are:

  • SEEK_SET-设定位置等于$offset字节。
  • SEEK_CUR-设定位置为当前位置加上$offset。
  • SEEK_END-设定位置为文件尾加上$offset。

返回值

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

范例

Example #1fseek()例子

注释

Note:

如果使用附加模试(aa+),任何写入文件数据都会被附加上去,而文件的位置将会被忽略,调用fseek()的结果尚未定义。Note:

Not all streams support seeking. For those that do not support seeking, forward seeking from the current position is accomplished by reading and discarding data; other forms of seeking will fail.

参见

  • ftell() 返回文件指针读/写的位置
  • rewind() 倒回文件指针的位置
JUST TO QUOTE AND POINT THIS OUT:
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
3. if you're using fseek() to write data to a file, remember to open the file in "r+" 
mode, example:
 $fp=fopen($filename,"r+");
DON'T open the file in mode "a" (for append), because it puts
 the file pointer at the end of the file and doesn't let you 
fseek earlier positions in the file (it didn't for me!). Also, 
don't open the file in mode "w" -- although this puts you at 
the beginning of the file -- because it wipes out all data in 
the file. 
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Took me half a day to figure :/
The official docs indicate that not all streams are seekable.
You can try to seek anyway and handle failure:

Or, you can use the stream_get_meta_data function:
http://php.net/stream_get_meta_data 
I want to give my contribution about the "read last lines from a file" topic. I've done some researches (starting from here, really) and run many tests for different algorithms and scenarios, and came up with this:
What is the best way in PHP to read last lines from a file?
http://stackoverflow.com/a/15025877/995958
In that mini-article I tried to analyze all different methods and their performance over different files.
Hope it helps.
I tried to improve and modify (mail at ulf-kosack dot de)'s function. Actually it is very fast, i.e. requires much less time than to get the last five, ten or whatever lines of a file using file() ore file_get_contents().
function read_file($file, $lines)
{
    $handle = fopen($file, "r");
    $linecounter = $lines;
    $pos = -2;
    $beginning = false;
    $text = array();
    while ($linecounter > 0) {
     $t = " ";
     while ($t != "\n") {
      if(fseek($handle, $pos, SEEK_END) == -1) {
$beginning = true; break; }
      $t = fgetc($handle);
      $pos --;
     }
     $linecounter --;
     if($beginning) rewind($handle);
     $text[$lines-$linecounter-1] = fgets($handle);
     if($beginning break;
    }
    fclose ($handle);
    return array_reverse($text); // array_reverse is optional: you can also just return the $text array which consists of the file's lines. 
}
The good thing now is, that you don't get an error when your requesting more lines than the file contains. In this case the function will just return the whole file content.
Write Dummy File 4GB in Php 32bits (X86)
if you want write more GB File (>4GB), use Php(X64) .
this file is created in 0.0041329860687256 second
CreatFileDummy('data_test.txt',4294967296);
FUNCTION CreatFileDummy($file_name,$size) {  
// 32bits 4 294 967 296 bytes MAX Size 
  $f = fopen($file_name, 'wb');
  if($size >= 1000000000) {
    $z = ($size / 1000000000);    
    if (is_float($z)) { 
      $z = round($z,0);
      fseek($f, ( $size - ($z * 1000000000) -1 ), SEEK_END);
      fwrite($f, "\0");
    }    
    while(--$z > -1) {
      fseek($f, 999999999, SEEK_END);
      fwrite($f, "\0");
    }
  } 
  else {
    fseek($f, $size - 1, SEEK_END);
    fwrite($f, "\0");
  }
  fclose($f);
Return true;
}
Synx
To:seeker at example com
Be careful, though. 
You can freely position you pointer if you open a file in (r+) mode, but it will "overwrite" the data, not "append it".
Tested this:

New contents of the file.txt will be like this:
"want to add thiste your notes to the PHP manual from the comfort of your browser!".
If you really want to append at the beginning, you have to first get all the contents, save it, clear the file, put the new contents and append the saved contents at the end.
Based on the function below, provided by info at o08 dot com (thanks), the following should enable you to read a single line from a file, identified by the line number (starting with 1): 
Don't use filesize() on files that may be accessed and updated by parallel processes or threads (as the filesize() return value is maintained in a cache).
Instead lock the opened file and use fseek($fp,0,SEEK_END) and ftell($fp) to get the actual filesize if you need to perform a fread() call to read the whole file...
Here is a function that returns the last line of a file. This should be quicker than reading the whole file till you get to the last line. If you want to speed it up a bit, you can set the $pos = some number that is just greater than the line length. The files I was dealing with were various lengths, so this worked for me. 
how to read BIG files using fseek (above 2GB+, upto any size like 4GB+, 100GB+, 100 terabyes+, any file size, 100 petabytes, max limit is php_float_max ) ?
// seek / set file pointer to 50 GB
my_fseek($fp, floatval(50000000000),1);
function my_fseek($fp,$pos,$first=0) {
// set to 0 pos initially, one-time
if($first) fseek($fp,0,SEEK_SET);
// get pos float value
$pos=floatval($pos);
 // within limits, use normal fseek
if($pos
A little correction for code to read last line from chenganeyou at eyou dot com.
$linenumber = sizeof($file)-1;
should be
$linenumber = sizeof($contents)-1;
because sizeof will count array element, not file size. 
sometimes we want read file from last line to beginning of file.I use the following.

Enjoy! Mail me if it works! ;-)
I use the following codes to read the last line of a file.
Compared to jim at lfchosting dot com, it should be more efficient. 
This a tail php script example for windows system. 
Thanks to Dan, whose above comment provided a key to solve the issue of how to append to a file. 
   After, using phpinfo(); I made sure my installation of PHP had the requisite settings mentioned in the text to the manual entry for fopen(), I was puzzled as to why my use of fopen() with the append option 'a' (append option) didn't work. Then I read a comment contributed to Appendix L (http://us2.php.net/manual/en/wrappers.php) that the append option 'a' for fopen() doesn't work as expected. The writer suggested using the 'w' option instead, which I found did work. But the 'w' option (write option) overwrites everything in the file.
   The question remained how to accomplish appending. Following Dan's suggestion about the 'r+' option, I tried this, which works fine:
    $string = "Message to write to log";
    $filehandle = fopen ("/home/name/sqllogs/phpsqlerr.txt", 'r+');
  fseek ( $filehandle,0, SEEK_END);
  fwrite ( $filehandle, $string."\n" );
  fclose ($filehandle);
In order to read a text file from end->beginning e.g display the most recent contents of a log file first. I use the following.
It basically just uses fseek to find the end of the file, ftell to find the byte count for a counter, then iterates backwards through the file using fgetc to test for the newline charater.
$i=0 ;
$lines=500 ;
$fp = fopen($log,"r") ;
if(is_resource($fp)){
  fseek($fp,0,SEEK_END) ;
  $a = ftell($fp) ;
  while($i 
Jim's (jim at lfchosting dot com) code for the last-line issue is perfect if the file is not empty, or moreover if it has more than one line. However if the file you're using cotains no new-line character at all (i.e. it is empty or it's got one line and only one) the while loop will stuck indefinitely.
I know this script is meant for big files which would always contain at least several lines, but it would be clever to make the script error-proof.
Thus, here's a little modification to his code.

鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com

免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)

图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)