By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

Read a File With AutoIt

How to read a file into a variable with AutoIt, or how to read one character at a time.

Edited: 2015-02-13 00:24

AutoIt Logo

In this Tutorial you will learn how to read a file into a variable with AutoIt, which perhaps is what most people are looking for when they want to read a file. Reading a file is done with the FileRead function, which is used after opening the file for reading.

Read file into variable using AutoIt

The below example starts by opening the file for reading, this is done using the FileOpen function – do not think to much about this function for now, you can always look it up in our reference if need to.

$file = FileOpen("test.txt", 0)

The next line reads the content of the file into a variable. The FileRead function does this by default, so there is no need to use extra parameters.

$FileContent = FileRead($file)
MsgBox(0, "Content:", $FileContent)

The final line simply closes the file after having read it into your variable.

FileClose($file)

And the full script:

$file = FileOpen("test.txt", 0)

    $FileContent = FileRead($file)
    MsgBox(0, "Content:", $FileContent)

FileClose($file)

Read the file x characters at a time

The parameter provided in the FileRead function in this example, tells the function how many characters should be read at a time.

$file = FileOpen("test.txt", 0)
While 1
    $chars = FileRead($file, 1)
    If @error = -1 Then ExitLoop
    MsgBox(0, "Char read:", $chars)
Wend
FileClose($file)

Setting this at 2 will read two characters at a time, 3 three, and so on.

Next Tutorial: Write Content to a File with AutoIt