Tuesday, November 24, 2009

Retrieve the lines from the end of the file. (from the last line)

/**
 * Retrieve the lines from the end of the file. (from the last line);
 * @param 
 * @return 
 */
function _tail($filename, $num = 1, $return_type = 'str') {
  $lineArr = array();

  if (file_exists($filename)) {
    $line_count = 0;

    $fp = fopen($filename, "r");
    fseek($fp, 0, SEEK_END);
    $seek_count = ftell($fp);

    while ($seek_count >= 0 && $line_count < $num) {
      $char = fgetc($fp);
      
      if (ord($char) == 10 || $seek_count == 0) {
        if ($seek_count == 0) {
          $seek_count--;
        }
        fseek($fp, $seek_count + 1, SEEK_SET);
        $lineArr[] = fgets($fp);
      }

      $seek_count--;
      fseek($fp, $seek_count, SEEK_SET);
    }

    fclose($fp);
  }

  return $lineArr;
}

/**
 * Retrieve the characters backward from a file.
 * @param $return_type: can be either "str" or "arr"
 * @return 
 */
function _tail_v2($filename, $num = 1, $return_type = 'str') {
  $lineArr = array();

  if (file_exists($filename)) {
    $line = NULL;
    $line_count = 0;

    $fp = fopen($filename, "r");
    fseek($fp, 0, SEEK_END);
    $seek_count = ftell($fp);

    while ($seek_count >= 0 && $line_count < $num) {
      $char = fgetc($fp);
      $seek_count--;
      fseek($fp, $seek_count, SEEK_SET);

      if (ord($char) == 13) {
        continue;
      }

      $line .= $char;

      if (ord($char) == 10 || $seek_count == -1) {
        if ($return_type === 'arr') {
          $lineArr[] = $line;
          $line = '';
        }

        $line_count++;
      }
    }

    fclose($fp);
  }

  return $return_type === 'str' ? $line : $lineArr;
}

No comments: