Lua程序設計第4版第7章課後練習答案

7.1

function f71(infile,outfile)
    -- 重定向輸出
    if outfile then
        if assert(io.open(outfile)) then
            print("if you confirm prease print 1")
            local confirm = io.read("n")
            if confirm ==1 then
                io.output(outfile)
            end
        end
    end
    -- 重定向輸入
    if infile then
        io.input(infile)
    end
    local block = {}
    for line in io.lines() do
        block[#block+1] = line
    end
    table.sort(block)
    for i = 1, #block do
        io.write(block[i].."\n")
    end
    io.close()
end

7.2 同上

7.3

function f73(infile)
    local t1 = os.clock()
    io.input(infile)
    --按字符
    f73_1()
    --按行
    --f73_2()
    --按塊
    --f73_3()
    --整個文件
    --f73_4()
    io.close()
    print("\n"..os.clock()-t1)
end

function f73_1()
    for i = 1, math.huge do
        local c = io.read(1)
        if c==nil then
            break
        end
        io.write(c)
    end
end

function f73_2()
    for i = 1, math.huge do
        local c = io.read("L")
        if c==nil then
            break
        end
        io.write(c)
    end
end

function f73_3()
    for i = 1, math.huge do
        local c = io.read(2^13)
        if c==nil then
            break
        end
        io.write(c)
    end
end

function f73_4()
    local c = io.read("a")
    io.write(c)
end

結果爲:
239kb的一個文件
0.15 0.064 0008 0.013
最好的是按快讀取

7.4, 7.5

function f74(infile,n)
    if n==nil then
        n = 1
    end
    io.input(infile)
    local size = io.input():seek("end")
    for i = 1, n do
        local c = ""
        while c~="\n" do
            io.input():seek("cur",-1)
            c = io.read(1)
            io.input():seek("cur",-1)
        end
        io.input():seek("cur",-1)
    end
    local l = io.read()
    while l~=nil do
        io.write(l)
        l = io.read("L")
    end
    io.close()
end

7.6

os.execute("mkdir dir")
os.execute("rmdir dirname")
os.execute("dir dirname")
popen同上

function f76(dirname)
    os.execute("dir /B /O:S "..dirname)
end
f76("dir01")

7.7
不能,不可以改變正在運行文件的路徑

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章