I/O Library

References

The Simple I/O Model

  • Commonly uses stdin (input) and stdout (output)
    • This can be changed using io.input(filename) and io.output(filename)

Writing to stdout or a file

io.write("this is an output string to the console\n") io.output("C:\\lua Programming\\myOutputFile.txt") io.write("this is an output string to a file\n") io.write("this is an second output string to a file") io.flush() io.close() stdoutFile = io.stdout --reset to stdout io.output(stdoutFile) io.write("This is another output string to the console")

Reading from stdin or a file

  • The io.read command takes one argument
    • They control what to read

"*a" - read the whole file "*l" - read the next line does not return the newline "*L" - read the next line returns the newline also "*n" - read a number num - read a string with up to num characters

  • The following is an example of reading
    • First from stdin with a prompt
    • Then from a file after switching to a file
    • Then back to stdin in with a prompt after switching back to stdin

print('Enter your First Name:') local firstName = io.read('*l') io.input("C:\\lua Programming\\myInputFile.txt") local theString = io.read('*L') io.write(theString) theString = io.read('*l') io.write(theString) stdinFile = io.stdin --reset to stdout io.input(stdinFile) print('\n\nEnter your Last Name:') local lastName = io.read('*L') io.write("Thanks for the input " .. firstName .. " " .. lastName)

The Complete I/O Model

  • based on file handles

    • An open file with a current position
      • Open a file using the io.open function
      • Plus a mode string 'r' or 'w' or 'a'
          • read, write, append
      • Returns a new handle for the file

      • In case of error returns nil

Input

local file = assert(io.open(filename, "r")) local text = file:read("*a") -- read the entire file file:close()

Output

local file = assert(io.open(filename, "w")) file:write("something") file:flush() file:close()

An example of Reading a file

local BUFSIZE = 2^5 local filePath = "C:\\lua Programming\\wordcount.txt" local file = io.input(filePath) local cc, lc, wc = 0, 0, 0 -- character line and word counts for lines, rest in io.lines(arg[1], BUFSIZE, "*L") do if rest then lines = lines .. rest end cc = cc + #lines -- count words local _, t = string.gsub(lines,"%S+","") wc = wc + t -- count newlines _, t = string.gsub(lines,"\n","\n") lc = lc + t end file:close() print(lc, wc, cc)

References