# encoding: ascii
# api: powershell
# title: Tac (reverse cat)
# description: Originally posted by Keith Hill on microsoft.public.windows.powershell.
# version: 0.1
# author: halr9000
# license: CC0
# x-poshcode-id: 433
# x-archived: 2017-05-22T03:52:08
# x-published: 2009-06-26T07:20:00
#
# This script reads the content of a file backwards, from the end to the beginning.
# NOTE: a space is inserted between every char if the file is Unicode
#
# From "Unix like command for tac?" thread on posh NG
# solution by Keith Hill

param([string]$path)

$fs = New-Object System.IO.FileStream ((Resolve-Path $path), 'Open', 'Read')
trap { $fs.Close(); break }

$pos = $fs.Length
$sb = New-Object System.Text.StringBuilder
while (--$pos -ge 0) {
    [void]$fs.Seek($pos, 'Begin')
    $ch = [char]$fs.ReadByte()
    if ($ch -eq "`n" -and $sb.Length -gt 0) {
        $sb.ToString().TrimEnd()
        $sb.Length = 0
    }
    [void]$sb.Insert(0, [char]$ch)
}
$sb.ToString().TrimEnd()
