PHP中的随机访问文件

Ale*_*lex 0 php file random-access

是否有一些PHP函数或类允许我读取像字符数组的文件?

例如:

$string = str_split('blabla');

$i = 0;

switch($string[$i]){

  case 'x':
    do_something();
    $i++;


  case 'y':
    if(isset($string[++$i]))
      do_something_else();
    else
      break;

   case 'z':
      // recursive call of this code etc..

}
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用$string = file_get_contents($file),但问题是我得到了一个用于800K小文件(如80MB)的大量内存.

所以,我可以以某种方式"上传"上面代码中的文件,类似于在调用isset()时自动从文件中读取数据的类访问?:)

Jon*_*ier 5

您可以使用fseekfgetc在文件中跳转并一次读取单个字符.

// Leaves the file handle modified
function get_char($file, $char) {
   fseek($file, $char);
   return fgetc($file);
}
Run Code Online (Sandbox Code Playgroud)

你特别提到了你想要的数组行为.您可以构建一个实现ArrayAccess支持它的类.

由于以下几个原因,这可能很危险:

  • 您需要防止$char请求索引超过文件长度的输入
  • 文件句柄将不断变异(应该没问题,只要你不在其他地方使用它)
  • 这可能效率低下(通过缓存过去的请求来抵消)

稍微更有效的替代方案是"懒惰地"读取文件(即,以块的形式而不是一次性读取它).这是一些(未经测试的)代码:

class BufferedReader {
    // The size of a chunk in bytes
    const BUFFER_SIZE = 512;

    protected $file;
    protected $data;

    function __construct($fname) {
        $this->file = fopen($fname, 'r');
    }

    function read_buffer() {
        $this->data .= fread($this->file, self::BUFFER_SIZE);
    }

    function get_char($char) {
        while ( $char >= strlen($this->data) && !feof($this->file) ) {
            $this->read_buffer();
        }

        if ( $char >= strlen($this->data) ) {
            return FALSE;
        }

        return substr($this->data, $char, 1);
    }
}
Run Code Online (Sandbox Code Playgroud)