user6022288
user6022288

Reputation:

Reading file character by character to array

I was searching for long time, how to read whole file into character array. My current code:

function readWholeFile(fn)
  if(fn==nil) then 
    return nil 
  end
  local file = io.open(fn, "r")
  return file:read("*a")
end

I want to this function return

{'s', 'o', 'm', 'e', 't', 'e', 'x', 't'}

instead of

"Sometext"

So how to do this?

Upvotes: 2

Views: 1897

Answers (2)

Alexander Altshuler
Alexander Altshuler

Reputation: 3064

gmatch works with patterns, it looks a bit overkill IMHO, all you need is string.sub()

local text = readWholeFile("filename")
local t = {}
for i=1, #text do t[#t + 1] = text:sub(i,1) end

Upvotes: 1

Yu Hao
Yu Hao

Reputation: 122493

Read the whole file as you did, and split the content string into characters. This could be done easily with the string library. e.g:

for c in content:gmatch(".") do

Another possible solution:

file:read supports several formats, file:read("*a") is the way to read the whole file. Instead, use file:read(1) to read one character each time, e.g:

repeat
  local c = file:read(1)
  print(c)
until c == nil

Upvotes: 4

Related Questions