Lua Programming 4th edition answers to the exercises in Chapter 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 above

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

Results:
239KB of a file
0.15 0.064 0008 0.013
best fast read by

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
can not, can not change the running path of the file

Published 76 original articles · won praise 7 · views 10000 +

Guess you like

Origin blog.csdn.net/Icecoldless/article/details/104080176