Lua基础:IO库

I/O 库为文件操作提供两种模式。简单模式(simple model)拥有一个当前输入文件和一个当前输出文件,并且提供针对这些文件相关的操作。完全模式(complete model)使用外部的文件句柄来实现。

  1. "*all" 读取整个文件
  2. "*line" 读取下一行
  3. "*number" 从串中转换出一个数值
  4. num 读取 num 个字符到串

简单模式:

  1. io.write("hello", "Lua"); io.write("Hi", "\n")          --io.write
  2.  io.write(string.format("sin (3) = %.4f\n", math.sin(3)))  
  3.  
  4. local line = io.read()                                            --io.read
  5. local block = io.read(size) 

完全模式:类似C语言的文件流FILE*

  1. io.open(filename, mode)   --打开文件,mode: r读,w写,a追加, b二进制
  2. local f = assert(io.open(filename, mode))  --查错
  3. -------------------------------------------------------------------
  4. local f = assert(io.open(filename, "r"))   --打开文件读
  5. local t = f:read("*all")       --读取整个文件
  6. f:close()                            --关闭文件
  7. --------------------------------------------------------------以固定大小读取文件
  8. local BUFSIZE = 2^13                      -- 8K
  9. local f = io.input(arg[1])                     -- open input file
  10. local cc, lc, wc = 0, 0, 0                     -- char, line, and word counts
  11. while true do
  12.      local lines, rest = f:read(BUFSIZE, "*line")
  13.      if not lines then break end
  14.      if rest then lines = lines .. rest .. '\n' end
  15.      cc = cc + string.len(lines)
  16.         -- count words in the chunk
  17.      local _,t = string.gsub(lines, "%S+", "")
  18.       wc = wc + t
  19.       -- count newlines in the chunk
  20.       _,t = string.gsub(lines, "\n", "\n")
  21.      lc = lc + t
  22. end
  23. print(lc, wc, cc)
  24. ------------------------------------------------------
  25. 二进制文件
  26. local inp = assert(io.open(arg[1], "rb"))          --读二进制
  27. local out = assert(io.open(arg[2], "wb"))        --写二进制
  28.  
  29. local data = inp:read("*all") 
  30. data = string.gsub(data, "\r\n", "\n") 
  31.  
  32. out:write(data) 
  33. assert(out:close()) 
  34. -----------------------------------------文件大小
  35. function fsize (file) 
  36.         local current = file:seek()          -- get current position 
  37.         local size = file:seek("end")         -- get file size 
  38.         file:seek("set", current)         -- restore position 
  39.        return size 
  40. end 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值