How do I read until the end of file?

我的未来我决定 提交于 2019-12-11 11:46:08

问题


In C, I can read an input and stop the program when it reaches the end of file (EOF). Like so.

#include <stdio.h>

int main(void) {
    int a;       
    while (scanf("%d", &a) != EOF)
        printf("%d\n", a);
    return 0;
}

How can I do that in Lua?


回答1:


The Lua Documentation features a ton of details on file-reading and other IO. For reading an entire file:

t = io.read("*all")

apparently reads an entire file. The documentation has examples on reading line-by-line etc. Hope this helps.

Example on reading all lines of a file and numbering each of them (line-by-line):

   local count = 1
    while true do
      local line = io.read()
      if line == nil then break end
      io.write(string.format("%6d  ", count), line, "\n")
      count = count + 1
    end



回答2:


For a similar program in lua, you can read it line by line and check if the line is nil(which is returned when the line is EOF).

while true do
  local line = io.read()
  if (line == nil) then break end
end


来源:https://stackoverflow.com/questions/5094417/how-do-i-read-until-the-end-of-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!