-- 4.宣告一個function,輸入任意一個文字檔案的路徑,將內容打印出來,若檔案路徑找不到檔案要報錯



function readFile(fileName)
    local file = io.open(fileName, "r")
    local content = file:read("*all")     --*all表示讀取所有內容,*line表示讀取一行內容,*number表示讀取一個數字,如果第一個字元為數字則返回這個數字,否則返回nil
    file:close()
    return content
end


function file_exists(name)
    local file = io.open(name, "r")
    if file ~= nil  
    then 
        io.close(file) 
        return true 
    else 
        return false 
    end
end

 

function EX_4(Path)
    if (type(Path)=="string" and file_exists(Path))
    then
        print(readFile(Path))
    else
        print("Error, can't find the file")
    end
end 

EX_4("/Users/ellenlin/Downloads/20220517.txt")

Embed on website

To embed this program on your website, copy the following code and paste it into your website's HTML: