Jump to content

FileReadLastChars


Zedna
 Share

Recommended Posts

#include <WinAPI.au3>

$text = FileReadLastChars("C:\Program Files\AutoIt3\Include\Array.au3", 1024)
MsgBox(0, 'FileReadLastChars', $text)

Func FileReadLastChars($sFile, $nChars)
    Local $nBytes
    $tBuffer = DLLStructCreate("char["&$nChars&"]")
    $hFile = _WinAPI_CreateFile($sFile, 2, 2) ; open for read
    _WinAPI_SetFilePointer($hFile, -1 * $nChars, 2) ; from end
    _WinAPI_ReadFile($hFile, DLLStructGetPtr($tBuffer), $nChars, $nBytes)
    _WinAPI_CloseHandle($hFile)
    Return DLLStructGetData($tBuffer, 1)
EndFunc

; included as standard UDF since AutoIt 3.2.13.6 version
Func _WinAPI_SetFilePointer($hFile, $iPos, $iMethod = 0)
    $aResult = DllCall( "kernel32.dll", "long", "SetFilePointer", "hwnd", $hFile, "long", $iPos, "long_ptr", 0, "long", $iMethod)
    If @error Then Return SetError(1, 0, -1)
    If $aResult[0] = -1 Then Return SetError(2, 0, -1) ; $INVALID_SET_FILE_POINTER = -1
    Return $aResult[0]
EndFunc ;==>_WinAPI_SetFilePointer

Here is my topic about _WinAPI_SetFilePointer()

 

EDIT: simpler version compatible with latest AutoIt

$text = FileReadLastChars("C:\Program Files\AutoIt3\Include\Array.au3", 1024)
MsgBox(0, 'FileReadLastChars', $text)

Func FileReadLastChars($sFile , $nChars)
    $hFile = FileOpen($sFile, 0) ; open for read
    FileSetPos($hFile, -1 * $nChars, 2) ; from end
    $sRet = FileRead($hFile)
    FileClose($hFile)
    Return $sRet
EndFunc

 

Edited by Zedna
added simpler version compatible with latest AutoIt
Link to comment
Share on other sites

Link to comment
Share on other sites

Thanks Zedna. Here is a native version...
 

#include <FileConstants.au3>
#include <MsgBoxConstants.au3>

Global Enum Step * 2 $FRLC_FILENOTEXISTS, $FRLC_ISNOTDIGIT, $FRLC_OUTOFBOUNDS, $FRLC_ENDOFFILE

Local $sText = FileReadLastChars(@ScriptFullPath, 204)
ConsoleWrite('@error: ' & @error & ', Text: ' & $sText & @CRLF)
MsgBox($MB_SYSTEMMODAL, 'FileReadLastChars', $sText)

Func FileReadLastChars($sFilePath, $iChars) ; Idea by Zedna, created by guinness
    Local $sData = ''
    Local $hFileOpen = FileOpen($sFilePath, $FO_READ)
    If $hFileOpen = -1 Then Return SetError($FRLC_FILENOTEXISTS, 0, $sData) ; If the file doesn't exist or an unexpected error occurred
    If IsString($iChars) Then ; If $iChars happens to be a string
        If Not StringIsDigit($iChars) Then
            FileClose($hFileOpen)
            Return SetError($FRLC_ISNOTDIGIT, 0, $sData) ; If not an string representing an integer then set an @error
        EndIf
        $iChars = Int($iChars) ; Parse as an integer
    EndIf

    If $iChars <= 0 Or $iChars > FileGetSize($sFilePath) Then
        FileClose($hFileOpen)
        Return SetError($FRLC_OUTOFBOUNDS, 0, $sData) ; If less than or equal to zero or greater than the file size
    EndIf

    If FileSetPos($hFileOpen, -1 * $iChars, $FILE_END) Then
        $sData = FileRead($hFileOpen, $iChars) ; Read the file based on the position and number of chars
        If @error Then
            FileClose($hFileOpen)
            Return SetError($FRLC_ENDOFFILE, 0, $sData)
        EndIf
    EndIf

    FileClose($hFileOpen)
    Return $sData
EndFunc   ;==>FileReadLastChars

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

msgbox(0, '' , _FileReadLastChar(@ScriptFullPath , 7))

Func _FileReadLastChar($file , $count)
    $hFile = FileOpen($file)
    $pos = FileSetPos($hFile , $count * -1 , 2)
    $sOut = FileRead($hFile)
    return $sOut
EndFunc

Edited by boththose

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Link to comment
Share on other sites

Learn how to error check, especially when you're creating a UDF.

 

msgbox(0, '' , _FileReadLastChar(@ScriptFullPath , 7))

Func _FileReadLastChar($file , $count)
    $hFile = FileOpen($file)
    $pos = FileSetPos($hFile , $count * -1 , 2)
    $sOut = FileRead($hFile)
    return $sOut
EndFunc

This is wrong. Please read the help file again as cleaning up resources is important. Edited by guinness

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

Good thing I wasnt making a UDF, and only clearly showing concept.  And it gives the correct answer every time in reasonable tests.  Checks are sure in order for exceeding bounds, and  I'm sure in production they would close the handle.

Exit, 

that is more,    _FileReadTheWholeThing_ThenReturnTheLastChars

Edited by boththose

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Link to comment
Share on other sites


What is the advantage of this rather than using the built-in commands?

 

My function (using Win32 API) is the only one which works with old AutoIt 3.2.12.1 which is my main AutoIt's version.

Native FileSetPos() function and even _WinAPI_SetFilePointer() were introduced later.

Edited by Zedna
Link to comment
Share on other sites

Link to comment
Share on other sites

  • 2 years later...

According to FileReadLastChars() in first post here is also derived FileReadFirstChars().

It can be very usefull when you need to read only small part at beginning of big file,

because this function will not read whole content of file into memory, instead only desired small part.

Note: FileSetPos() in this case probably is not needed, because after FileOpen() file pointer should be at position 0 ...

 

compatible with latest AutoIt:

Func FileReadFirstChars($sFile , $nChars)
    $hFile = FileOpen($sFile, 0) ; open for read
    FileSetPos($hFile, 0, 0) ; from begin
    $sRet = FileRead($hFile, $nChars)
    FileClose($hFile)
    Return $sRet
EndFunc

 

compatible with older AutoIt (3.2.12.1):

Func FileReadFirstChars($sFile, $nChars)
    Local $nBytes
    $tBuffer = DLLStructCreate("char["&$nChars&"]")
    $hFile = _WinAPI_CreateFile($sFile, 2, 2) ; open for read
    _WinAPI_SetFilePointer($hFile, 0, 0) ; from begin
    _WinAPI_ReadFile($hFile, DLLStructGetPtr($tBuffer), $nChars, $nBytes)
    _WinAPI_CloseHandle($hFile)
    Return DLLStructGetData($tBuffer, 1)
EndFunc

 

Edited by Zedna
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...