सामग्री पर जाएँ

कंप्यूटर प्रोग्रामिंग/फ़ाइलें/लुआ

विकिविश्वविद्यालय से
-- This program creates a file, adds data to the file, displays the file,
-- appends more data to the file, displays the file, and then deletes the file.
-- It will not run if the file already exists.

function create_file(filename)
    local file 
    
    file = io.open(filename, "w")
    file:write("C\tF\n")
    for c = 0, 50, 1 do
        f = c * 9 / 5 + 32
        file:write(c .. "\t" .. f .. "\n")
    end
    file:close()
end

function read_file(filename)
    local file 
    local line
    
    file = io.open(filename, "r")
    while true do
        line = file:read()
        if line == nil then 
            break 
        end
        io.write(line, "\n")
    end
    file:close()
    io.write("\n")
end

function append_file(filename)
    local file = io.open(filename, "a")
    for c = 51, 100, 1 do
        f = c * 9 / 5 + 32
        file:write(c .. "\t" .. f .. "\n")
    end
    file:close()
end

function delete_file(filename)
    os.remove(filename)
end

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

function main()
    local filename = "~file.txt"

    if file_exists(filename) then
        io.write("File already exists.")
    else
        create_file(filename)
        read_file(filename)
        append_file(filename)
        read_file(filename)
        delete_file(filename)
    end
end
    
main()

निम्न कोड मुफ्त ऑनलाइन विकास के वातावरण में से एक में ऊपर कॉपी और पेस्ट करो या अपने खुद के कम्पाइलर/इंटरप्रेटर/आईडीई का उपयोग करें।