Компьютерный форум OSzone.net  

Компьютерный форум OSzone.net (http://forum.oszone.net/index.php)
-   AutoIt (http://forum.oszone.net/forumdisplay.php?f=103)
-   -   [решено] Чтение строк из лога и запись их в файл (http://forum.oszone.net/showthread.php?t=241205)

support23 23-08-2012 13:12 1975380

Чтение строк из лога и запись их в файл
 
Добрый день!
Есть необходимость прочитать N последних строк из файла (например log.txt)
и записать эти строки в файл (например task.txt)
вот что получилось, но скрипт работает корректно только с 5 последними строками, что нужно изменить чтобы увеличить кол-во обрабатываемых строк?

Код:

#include <FileConstants.au3>
$Pos = 1000
$space = "-----------------------------"
$hFile = FileOpen(@ScriptDir & '\log.txt')

FileSetPos($hFile, -196, $file_end)
$sText = FileRead($hFile)
FileClose($hFile)

For $i = 1 To 5
    $string = _ReadString($Pos, $i)
        FileWrite(@ScriptDir & "\task.txt", $string & @CRLF)
                ClipPut($string)
        Next
       
Func _ReadString(ByRef $Pos, $i)
    $TmpPos = StringInStr($sText, @CRLF, 0, -$i)
    $string = StringMid($sText, $TmpPos + 2, $Pos - $TmpPos - 2)
    $Pos = $TmpPos
    Return $string
EndFunc


madmasles 23-08-2012 19:52 1975652

support23,
Попробуйте так.
Код:

#include <Array.au3>

Dim $aError[5] = ['Успех', 'Не существует файла:', 'Пустой файл:', 'Ошибка открытия файла:', 'Ошибка чтения файла:']
$sFile = @ScriptFullPath
;$sFile = @ScriptDir & '\1.txt'
$iCount = Random(5, 15, 1)
ConsoleWrite($iCount & @LF)

$aLast = _FileReadLastLine($sFile, $iCount)
If @error Then
    MsgBox(16, 'Error', $aError[@error] & @LF & $sFile)
Else
    _ArrayDisplay($aLast, $aError[@error])
EndIf

Func _FileReadLastLine($s_File, $i_LastCount)
    ;$s_File - полный путь к файлу
    ;$i_LastCount - количество возвращаемых с конца строк
    ;Вернет массив $a_Ret с $i_LastCount последними строками, $a_Ret[0] = $i_LastCount
    ;пустые строки удаляются.
    Local $h_File, $i_Size, $s_Text, $aTemp, $i_Pos, $f_ExitLoop, $i_Start = 2, $a_Text, $a_Ret[2]
    If Not FileExists($s_File) Then Return SetError(1, 0, '')
    $i_Size = FileGetSize($s_File)
    If Not $i_Size Then Return SetError(2, 0, '')
    $h_File = FileOpen($s_File, 0)
    If $h_File = -1 Then Return SetError(3, 0, '')
    $i_Pos = $i_LastCount + 1
    While 1
        $s_Text = ''
        FileSetPos($h_File, -$i_Pos, 2)
        $s_Text = FileRead($h_File)
        $s_Text = StringRegExpReplace(StringStripCR($s_Text), '([\n]+$)', '')
        $s_Text = StringRegExpReplace($s_Text, '(\n){2,}', '$1')
        If $f_ExitLoop Then ExitLoop
        StringReplace($s_Text, @LF, '')
        If @extended >= $i_LastCount Then ExitLoop
        $i_Pos += $i_LastCount + 1
        If $i_Pos > $i_Size Then
            $f_ExitLoop = True
            $i_Start = 1
            $i_Pos = $i_Size
        EndIf
    WEnd
    FileClose($h_File)
    If Not $s_Text Then Return SetError(4, 0, '')
    $a_Text = StringSplit($s_Text, @LF)
    $s_Text = ''
    If $a_Text[0] > 1 Then
        If $f_ExitLoop Then
            ReDim $a_Ret[$a_Text[0] + 1]
        Else
            ReDim $a_Ret[$a_Text[0]]
        EndIf
        For $i = $i_Start To $a_Text[0]
            $a_Ret[0] += 1
            $a_Ret[$a_Ret[0]] = StringStripWS($a_Text[$i], 7)
        Next
    Else
        $a_Ret[0] = 1
        $a_Ret[1] = StringStripWS($a_Text[1], 7)
    EndIf
    Return $a_Ret
EndFunc  ;==>_FileReadLastLine


support23 24-08-2012 08:57 1975993

Не подскажите как сделать вывод строк в файл (сейчас отображаются в окне), и где в теле скрипта задается кол-во строк?

gora 05-10-2012 13:16 1999959

support23, может так:
Код:

#include <file.au3>

Local $aRecords
$i_LastCount = 5

If Not _FileReadToArray(@ScriptDir & '\log.txt', $aRecords) Then
    MsgBox(4096, "Ошибка", "Ошибка " & @error & " чтения файла в массив")
    Exit
EndIf
If $aRecords[0] <= $i_LastCount Then
    MsgBox(4096, "Ошибка", "В файле всего " & $aRecords[0] & " строк(и)")
    Exit
EndIf
_FileWriteFromArray(@ScriptDir & '\task.txt', $aRecords, $aRecords[0] - $i_LastCount + 1)
Exit


AZJIO 06-10-2012 04:39 2000317

Вот ещё по теме

support23, GUICtrlRead, FileWrite

support23 18-10-2012 12:04 2007753

Спасибо всем за помощь! мне подошел вариант который предложил gora


Время: 19:04.

Время: 19:04.
© OSzone.net 2001-