Advertisement
Guest User

dummydb.php

a guest
Feb 14th, 2012
308
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.37 KB | None | 0 0
  1. <?php
  2.  
  3. function build_index($source_file = 'source.txt', $index_file = 'index.dat')
  4. {
  5.     $offset = 0;
  6.     $lenght = 0;
  7.  
  8.     $index_fh = fopen($index_file, 'w');
  9.     $source_fh = fopen($source_file, 'r');
  10.  
  11.     while (($buff = fgets($source_fh)) !== false)
  12.     {
  13.         $length = strlen($buff);
  14.         // pack data and write to index.
  15.         // L unsigned long (always 32 bit, machine byte order)
  16.         // http://www.php.net/manual/en/function.pack.php
  17.         fwrite($index_fh, pack('LL', $offset, $length));
  18.         $offset += $length;
  19.     }
  20.     fclose($source_fh);
  21.     fclose($index_fh);
  22. }
  23.  
  24. // Размер придётся захардкодить или добавить подсчёт
  25. function get_data($source_file = 'source.txt', $index_file = 'index.dat', $string_count)
  26. {
  27.     // 2 * 4 byte
  28.     $index_data_size = 8;
  29.     $n = rand(0, $string_count - 1);
  30.  
  31.     // get offset:lenght pair from index
  32.     $index_fh = fopen($index_file, 'r');
  33.     fseek($index_fh, $n * $index_data_size);
  34.     $raw = unpack('L2', fread($index_fh, $index_data_size));
  35.     fclose($index_fh);
  36.    
  37.     // print_r($raw);
  38.     $offset = $raw[1];
  39.     $lenght = $raw[2];
  40.    
  41.     // get string from source
  42.     $source_fh = fopen($source_file, 'r');
  43.     fseek($source_fh, $offset);
  44.     $data = trim(fread($source_fh, $lenght));
  45.     fclose($source_fh);
  46.  
  47.     return $data;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement