1

I'm trying to concatenate every file in a folder in lua to compile a bunch of logs into one master log and send it off to someone. I'm using the ifs library to iterate through every file in a directory, then reading it all in and trying to append it to the master file.

for name in lfs.dir("logs") do
    if(name ~= "." and name ~= "..") then
     local path = "logs/"..name
     print (path)
     local file=io.open(path,"R")
     print "2"
     local content = io.read("*all")
     print "3"
     io.close(file)

     local f=io.open("log.csv","A")
     file:write(content)
     io.close(f)    
    end
end 

There are two issues. The ifs library returns "." and ".." before the other file names [is there a better way to ignore these than an if statement?] using the bit I found here: How to load all files from a directory?

The important issue is that my command prompt keeps crashing when I test the file. It prints the path (a good one), then it crashes before getting to the "2" and I'm not sure why. The file exists and I can manipulate it by adding lines to it in another function.

Any help would be greatly appreciated.

Community
  • 1
  • 1
Sambardo
  • 714
  • 2
  • 9
  • 15

1 Answers1

2

To avoid checking for "." and ".." you should use lfs.attributes and its mode field to see if each item is a file or directory (or something else).

Instead of io.read you probably want file:read -- this might be the cause of your "crash."

I suggest you use "r" and "a+" for the io.open mode arguments.

Oh, and use f:write to write content

Doug Currie
  • 40,708
  • 1
  • 95
  • 119
  • 1
    You should point out that `io.read` doesn't read from the `file`; it reads from a global file handle. A global file handle that was not opened. – Nicol Bolas Aug 01 '11 at 17:47
  • Also, curious if "R" vs. "r" is interpreted differently and what the + adds for "a+", as I haven't seen that before. – Sambardo Aug 04 '11 at 13:20
  • Re: lower case mode arguments... that's how they're documented at http://www.lua.org/manual/5.1/manual.html#pdf-io.open so that's what I'd use. – Doug Currie Aug 04 '11 at 17:22
  • Re: "a+"... the Lua documentation is a bit misleading (to me); in retrospect I think you're better off with "a". Also see http://stackoverflow.com/questions/3645123/opening-a-file-in-a-mode – Doug Currie Aug 04 '11 at 17:31
  • Sorry for the late reply, I didn't realize it wouldn't notify me of these comments too. Very helpful reading, thanks for the help. I think 'R' and 'r' both work the same, but to be safe I followed your advice :) – Sambardo Aug 11 '11 at 18:02