2011-02-23 46 views
1

在C中,我可以读取输入,并在程序到达文件末尾时停止该程序(EOF)。像这样。如何阅读文件结尾?

#include <stdio.h> 

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

我该如何在Lua中做到这一点?

回答

6

Lua Documentation具有大量关于文件读取和其他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 
+0

您的示例程序没有行编号,但引用了可打印编码。 (它应该更好地处理较低的控制字符,我想。) – 2011-02-23 20:50:38

+0

我的坏人 - 错误的例子被粘贴在:)这两个都在文档中可用:) – 2011-02-23 20:57:48

3

对于LUA一个类似的方案,可以通过线和检查线读取它如果该行是零(当行是EOF时返回)。

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

for s in io.lines()do something end – AndersH 2011-02-23 20:02:37

+0

@AndresH感谢您提供更清洁的解决方案。出于某种原因,我认为它不适用于标准输入。 – prasanna 2011-02-24 00:19:18