How to read a file line by line in crystal language?

Viewed 285

Hi I want to read a file line by line with crystal language, but I don't know how can I do that.

I read crystal documentation, but I couldn't find my answer.

It's my code:

system("ls /etc/NetworkManager/system-connections/ > Fox.txt")
file = File.read("Fox.txt")
system("sudo cat /etc/NetworkManager/system-connections/\'#{file}\' >> Fox_done.txt")
1 Answers

To read a file line by line, you can use File#each_line:

File.each_line("/path/to/input.txt") do |line|
  puts line
end

If the file is small and you want to load all lines in memory, you can also use File#read_lines:

File.read_lines("/path/to/input.txt") # returns a Array(String) 
Related