Jump to content

Read entire file: Difference between revisions

no edit summary
(Added Wren)
No edit summary
Line 421:
data)))</lang>
The macro '''with-open-file''' could be passed ''':external-format :utf-8''' on some implementations (which it would pass on to '''open''') so that reading would occur by unicode character but '''(file-length stream)''' would continue to return the number of bytes, not characters, necessary for storing it.
 
=={{header|Crystal}}==
The simplest way to read an entire file to a string is by using File.read:
 
<lang ruby>content = File.read("input.txt")
puts content</lang>
 
{{out}}
<pre>Lorem ipsum dolor sit amet, consectetur adipiscing elit nullam.</pre>
 
The encoding can also be specified:
 
<lang ruby>content = File.read("input.txt", "UTF-16")</lang>
 
or
 
<lang ruby>content = File.read("input.txt", encoding: "UTF-16")</lang>
 
File.open allows for more options and closes the file implicitly. Combine it with File#gets_to_end to read the entire file:
 
<lang ruby>content = File.open("input.txt", mode: "r", encoding: "UTF-8") do |file|
file.gets_to_end
end</lang>
 
Or no implicit closing at all with File.new:
 
<lang ruby>file = File.new("input.txt", mode: "r", encoding: "UTF-8")
content = file.gets_to_end
file.close</lang>
 
=={{header|D}}==
Cookies help us deliver our services. By using our services, you agree to our use of cookies.