Lua程序设计第4版第7章课后练习答案
程序员文章站
2024-03-17 23:01:16
...
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
不能,不可以改变正在运行文件的路径