ShareHolder Finder v0.9.3 is now released!!! Check Product Page for more details.


Wednesday, 23 March 2016

AutoIt - Read data from a file to an array

Author Post Date Wednesday, 23 March 2016
The data from a file can be read to a 1 dimensional array containing one line of text per element using FileReadToArray( "filehandle/filename" ) function. We can pass either the file handle returned by a call to FileOpen() or the file name string to read the data.
The function will return the array of data on success and @extended set to the number of lines read. Array UBound() function also can be used to determine the number of lines read.
In the case of failure, sets @error flag to non-zero. 1 = Error opening specified file and 2 = Empty file.


#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.")

;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 data into an array using the file handle.
Local $aArray = FileReadToArray($hFileOpen)

If @error Then
   MsgBox($MB_SYSTEMMODAL, "", "There was an error reading the file. @error: " & @error)
   For $i = 0 To UBound($aArray) - 1 ; Loop through the array.
    MsgBox($MB_SYSTEMMODAL, "", $aArray[$i]) ; Display the contents of the array.

;Close the handle returned by FileOpen.

Related Posts

Interesting? Share and Let Others Know.

Post a comment