Copy File (code snippet)

Description

Copies a file from one location to another, retaining the change date and access date.

Requires: lfs

Code

CopyFile.fh_lua
require "lfs"
function file_exists(name)
    local f=io.open(name,"r")
    if f~=nil then io.close(f) return true
    else
        return false
    end
end
 
function CopyFile(strfromfile,strtofile,bReplace)
    if not(bReplace) then
        if file_exists(strtofile) then
            return false
        end
    end
    local inp = assert(io.open(strfromfile, "rb"))
    local out = assert(io.open(strtofile, "wb"))
 
    local data = inp:read("*all")
    out:write(data)
    assert(inp:close())
    assert(out:close())
    -- Copy the last modification date and access date from the original.
    local attr = lfs.attributes(strfromfile)
    lfs.touch(strtofile,attr['modification'],attr['access'])
    return true
end
 
if CopyFile('c:\\temp\\picture.jpg','d:\\temp\\picture.jpg',true) then
    print("File Copied")
else
    print("File Skipped")
end