3

I have a path (as a string) to a directory. In that directory, are a bunch of text files. I want to go to that directory open it, and go to each text file and read the data.

I've tried

f = io.open(path)
f:read("*a")

I get the error "nil Is a directory"

I've tried:

f = io.popen(path)

I get the error: "Permission denied"

Is it just me, but it seems to be a lot harder than it should be to do basic file io in lua?

lars
  • 1,976
  • 5
  • 33
  • 47

2 Answers2

4

A directory isn't a file. You can't just open it.

And yes, lua itself has (intentionally) limited functionality.

You can use luafilesystem or luaposix and similar modules to get more features in this area.

Etan Reisner
  • 77,877
  • 8
  • 106
  • 148
  • Yes, a directory isn't just a file. But if you have a directory A that has a list of directories B_i and you want to open all the files in directory B_i and all you have is a path to directory A, it seems that there should be an easy way to do this. – lars Jun 10 '15 at 17:10
  • There is, mostly, when you have access to functions that support operations on directories. lua doesn't have those by default (for portability reasons). – Etan Reisner Jun 10 '15 at 17:12
4

You can also use the following script to list the names of the files in a given directory (assuming Unix/Posix):

dirname = '.'
f = io.popen('ls ' .. dirname)
for name in f:lines() do print(name) end
  • 2
    I would use `io.popen('/bin/ls ' .. dirname)` to make sure no one tricks our application into executing the first `ls` they happened to put on the PATH. – llogiq Jun 11 '15 at 08:49