LATEST UPDATES
ShareHolder Finder v0.9.3 is now released!!! Check Product Page for more details.
✉ info@automationdevelopers.com

ITS ALL ABOUT AUTOMATION

Wednesday, 23 March 2016

AutoIt - Read a specific line of data from a file


Author Post Date Wednesday, 23 March 2016
A specific line of text from a file can be read using FileReadLine( "filehandle/filename" [, line = 1] ) function. We can pass either the file handle returned by a call to FileOpen() or the file name string to read the data. The line number to read is optional and if not specified, the next line from the current file position will be read. The last line can be read by passing line number as -1.
The function will return the line of text on success and in the case of failure, sets @error flag to non-zero. 1 = if file not opened in read mode or other error. -1 = if end-of-file is reached.

Example:

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

;Assign the file path to a variable
Local $sFilePath = "C:\AutomationDevelopers\temp.txt"

;Open the file temp.txt in append mode. If the folder C:\AutomationDevelopers does not exist, it will be created.
Local $hFileOpen = FileOpen($sFilePath, $FO_APPEND + $FO_CREATEPATH)

;Display a message box in case of any errors.
If $hFileOpen = -1 Then
   MsgBox($MB_SYSTEMMODAL, "", "An error occurred when opening the file.")
EndIf

;Write a set of lines for demonstration
FileWriteLine($hFileOpen, "This is the first line")
FileWriteLine($hFileOpen, "This is the second line")
FileWriteLine($hFileOpen, "This is the third line")
FileWriteLine($hFileOpen, "This is the last line")

;Set the file position to beginning for reading the data from the beginning of the file.
FileSetPos($hFileOpen, 0, $FILE_BEGIN)

;Read the 2nd line of data from the file using the handle returned by FileOpen
Local $sFileRead = FileReadLine ($hFileOpen,2)

;Display the data.
MsgBox($MB_SYSTEMMODAL, "Automation Developers", "The second line is:" & @CRLF & $sFileRead)

;Read the last line of data from the file using the handle returned by FileOpen
Local $sFileRead = FileReadLine ($hFileOpen,-1)

;Display the data.
MsgBox($MB_SYSTEMMODAL, "Automation Developers", "The last line is:" & @CRLF & $sFileRead)

;Close the handle returned by FileOpen.
FileClose($hFileOpen)

Related Posts




Interesting? Share and Let Others Know.

Post a Comment