我该如何读取直到文件结尾?

在 C 语言中,我可以读入一个输入并在读到文件结束标志 (EOF) 时停止程序。如下所示。

#include <stdio.h>

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

那么在 Lua 中应该怎么做呢?

原文链接 https://stackoverflow.com/questions/5094417

点赞
stackoverflow用户557445
stackoverflow用户557445

Lua文档涵盖了大量关于文件读取和其他IO的详细信息。要读取整个文件:

t = io.read(“*all”)

似乎可以读取整个文件。文档中有逐行读取的示例等。希望这有所帮助。

逐行读取文件并为每行编号的示例:

   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
2011-02-23 17:28:13
stackoverflow用户18501
stackoverflow用户18501

对于 Lua 中类似的程序,您可以逐行阅读并检查行是否为 nil(当行为 EOF 时返回)。

while true do
  local line = io.read()
  if (line == nil) then break end
end
2011-02-23 17:32:38