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
不能,不可以改变正在运行文件的路径

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JustEasyCode

谢谢您

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值