Read entire file: Difference between revisions

From Rosetta Code
Content added Content deleted
(Applesoft BASIC)
 
(14 intermediate revisions by 10 users not shown)
Line 20: Line 20:
{{trans|Python}}
{{trans|Python}}


<lang 11l>File(filename).read()</lang>
<syntaxhighlight lang="11l">File(filename).read()</syntaxhighlight>


=={{header|8th}}==
=={{header|8th}}==
The "slurp" word will read the entire contents of the file into memory, as-is, and give a "buffer". The ">s" converts that to a string, again "as-is"
The "slurp" word will read the entire contents of the file into memory, as-is, and give a "buffer". The ">s" converts that to a string, again "as-is"
<lang forth>
<syntaxhighlight lang="forth">
"somefile.txt" f:slurp >s
"somefile.txt" f:slurp >s
</syntaxhighlight>
</lang>


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>proc MAIN()
<syntaxhighlight lang="action!">proc MAIN()
char array STRING
char array STRING
open (1,"D:FILE.TXT",4,0)
open (1,"D:FILE.TXT",4,0)
Line 36: Line 36:
return
return


</syntaxhighlight>
</lang>


=={{header|Ada}}==
=={{header|Ada}}==
Line 47: Line 47:
and then Ada.Direct_IO to read the whole file in one chunk:
and then Ada.Direct_IO to read the whole file in one chunk:


<lang Ada>with Ada.Directories,
<syntaxhighlight lang="ada">with Ada.Directories,
Ada.Direct_IO,
Ada.Direct_IO,
Ada.Text_IO;
Ada.Text_IO;
Line 69: Line 69:


Ada.Text_IO.Put (Contents);
Ada.Text_IO.Put (Contents);
end Whole_File;</lang>
end Whole_File;</syntaxhighlight>


This kind of solution is limited a bit by the fact that the GNAT implementation of Ada.Direct_IO first allocates a copy of the read object on the stack inside Ada.Direct_IO.Read. On Linux you can use the command "<code>limit stacksize 1024M</code>" to increase the available stack for your processes to 1Gb, which gives your program more freedom to use the stack for allocating objects.
This kind of solution is limited a bit by the fact that the GNAT implementation of Ada.Direct_IO first allocates a copy of the read object on the stack inside Ada.Direct_IO.Read. On Linux you can use the command "<code>limit stacksize 1024M</code>" to increase the available stack for your processes to 1Gb, which gives your program more freedom to use the stack for allocating objects.
Line 79: Line 79:
Mapping the whole file into the address space of your process and then overlaying the file with a String object.
Mapping the whole file into the address space of your process and then overlaying the file with a String object.


<lang Ada>with Ada.Text_IO,
<syntaxhighlight lang="ada">with Ada.Text_IO,
POSIX.IO,
POSIX.IO,
POSIX.Memory_Mapping,
POSIX.Memory_Mapping,
Line 113: Line 113:
Length => Text_Size);
Length => Text_Size);
Close (File => Text_File);
Close (File => Text_File);
end Read_Entire_File;</lang>
end Read_Entire_File;</syntaxhighlight>


Character encodings and their handling are not really specified in Ada. What Ada does specify is three different character types (and corresponding string types):
Character encodings and their handling are not really specified in Ada. What Ada does specify is three different character types (and corresponding string types):
Line 132: Line 132:


'''In official/standard ALGOL 68 only:'''
'''In official/standard ALGOL 68 only:'''
<lang algol68>MODE BOOK = FLEX[0]FLEX[0]FLEX[0]CHAR; ¢ pages of lines of characters ¢
<syntaxhighlight lang="algol68">MODE BOOK = FLEX[0]FLEX[0]FLEX[0]CHAR; ¢ pages of lines of characters ¢
BOOK book;
BOOK book;


Line 138: Line 138:
INT errno = open(book file, "book.txt", stand in channel);
INT errno = open(book file, "book.txt", stand in channel);


get(book file, book)</lang>
get(book file, book)</syntaxhighlight>


Once a "book" has been read into a '''book''' array it can still be associated
Once a "book" has been read into a '''book''' array it can still be associated
Line 147: Line 147:


'''In official/standard ALGOL 68 only:'''
'''In official/standard ALGOL 68 only:'''
<lang algol68>FILE cached book file;
<syntaxhighlight lang="algol68">FILE cached book file;
associate(cached book file, book)</lang>
associate(cached book file, book)</syntaxhighlight>


=={{header|Amazing Hopper}}==
=={{header|Amazing Hopper}}==
<p>Hopper only stores 1 BM of characters for each string variable. If the file to be read "all at once" exceeds that size, the file can be read, and every 1MB saved in a row of a dynamic array of strings, using the PUSH instruction for each portion read. In this way, it is possible to work with portions of a file.</p>
<p>Hopper only stores 1 BM of characters for each string variable. If the file to be read "all at once" exceeds that size, the file can be read, and every 1MB saved in a row of a dynamic array of strings, using the PUSH instruction for each portion read. In this way, it is possible to work with portions of a file.</p>
<p>For now, only a simple version is shown.</p>
<p>For now, only a simple version is shown.</p>
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#include <hopper.h>
#include <hopper.h>


Line 161: Line 161:
println ( "File loaded:\n",s )
println ( "File loaded:\n",s )
exit(0)
exit(0)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 175: Line 175:


=={{header|AppleScript}}==
=={{header|AppleScript}}==
<lang AppleScript>set pathToTextFile to ((path to desktop folder as string) & "testfile.txt")
<syntaxhighlight lang="applescript">set pathToTextFile to ((path to desktop folder as string) & "testfile.txt")


-- short way: open, read and close in one step
-- short way: open, read and close in one step
Line 183: Line 183:
set fileRef to open for access pathToTextFile
set fileRef to open for access pathToTextFile
set fileContent to read fileRef
set fileContent to read fileRef
close access fileRef</lang>
close access fileRef</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>contents: read "input.txt"</lang>
<syntaxhighlight lang="rebol">contents: read "input.txt"</syntaxhighlight>


=={{header|ATS}}==
=={{header|ATS}}==
There are various functions in the ATS prelude, including this one that is based on fread(3) and returns Strptr1:
There are various functions in the ATS prelude, including this one that is based on fread(3) and returns Strptr1:
<lang ats>val s = fileref_get_file_string (stdin_ref)</lang>
<syntaxhighlight lang="ats">val s = fileref_get_file_string (stdin_ref)</syntaxhighlight>
Because Strptr1 is a NUL-terminated string, fileref_get_file_string cannot be used for data that contains bytes equal to zero.
Because Strptr1 is a NUL-terminated string, fileref_get_file_string cannot be used for data that contains bytes equal to zero.


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">
<lang AutoHotKey>
fileread, varname, C:\filename.txt ; adding "MsgBox %varname%" (no quotes) to the next line will display the file contents.</lang>
fileread, varname, C:\filename.txt ; adding "MsgBox %varname%" (no quotes) to the next line will display the file contents.</syntaxhighlight>
This script works fine as-is provided C:\filename.txt exists.
This script works fine as-is provided C:\filename.txt exists.


=={{header|AutoIt}}==
=={{header|AutoIt}}==
<syntaxhighlight lang="autoit">
<lang AutoIt>
$fileOpen = FileOpen("file.txt")
$fileOpen = FileOpen("file.txt")
$fileRead = FileRead($fileOpen)
$fileRead = FileRead($fileOpen)
FileClose($fileOpen)
FileClose($fileOpen)
</syntaxhighlight>
</lang>


=={{header|AWK}}==
=={{header|AWK}}==
<lang awk>#!/usr/bin/awk -f
<syntaxhighlight lang="awk">#!/usr/bin/awk -f
BEGIN {
BEGIN {
## empty record separate,
## empty record separate,
Line 218: Line 218:
## no further line is read printed
## no further line is read printed
print "=== line "NR,":",$0;
print "=== line "NR,":",$0;
}</lang>
}</syntaxhighlight>


{{works with|gawk}}
{{works with|gawk}}
<lang awk>
<syntaxhighlight lang="awk">
#!/usr/bin/awk -f
#!/usr/bin/awk -f


Line 232: Line 232:


}
}
</syntaxhighlight>
</lang>


=={{header|BaCon}}==
=={{header|BaCon}}==
For string data:
For string data:


<lang qbasic>content$ = LOAD$(filename$)</lang>
<syntaxhighlight lang="qbasic">content$ = LOAD$(filename$)</syntaxhighlight>


For memory mapped binary data:
For memory mapped binary data:


<lang freebasic>binary = BLOAD("somefile.bin")
<syntaxhighlight lang="freebasic">binary = BLOAD("somefile.bin")
PRINT "First two bytes are: ", PEEK(binary), " ", PEEK(binary+1)
PRINT "First two bytes are: ", PEEK(binary), " ", PEEK(binary+1)
FREE binary</lang>
FREE binary</syntaxhighlight>


=={{header|BASIC}}==
=={{header|BASIC}}==
Line 251: Line 251:
{{works with|QBasic}}
{{works with|QBasic}}


<lang qbasic>DIM f AS STRING
<syntaxhighlight lang="qbasic">DIM f AS STRING
OPEN "file.txt" FOR BINARY AS 1
OPEN "file.txt" FOR BINARY AS 1
f = SPACE$(LOF(1))
f = SPACE$(LOF(1))
GET #1, 1, f
GET #1, 1, f
CLOSE 1</lang>
CLOSE 1</syntaxhighlight>


==={{header|Applesoft BASIC}}===
==={{header|Applesoft BASIC}}===
<lang gwbasic> 100 D$ = CHR$ (4)
<syntaxhighlight lang="gwbasic"> 100 D$ = CHR$ (4)
110 F$ = "INPUT.TXT"
110 F$ = "INPUT.TXT"
120 PRINT D$"VERIFY"F$
120 PRINT D$"VERIFY"F$
Line 272: Line 272:
220 EOF = PEEK (222) = 5
220 EOF = PEEK (222) = 5
230 IF NOT EOF THEN RESUME
230 IF NOT EOF THEN RESUME
240 PRINT D$"CLOSE"F$</lang>
240 PRINT D$"CLOSE"F$</syntaxhighlight>
==={{header|Commodore BASIC}}===
==={{header|Commodore BASIC}}===
<lang basic>10 rem load the entire contents of some text file as a single string variable.
<syntaxhighlight lang="basic">10 rem load the entire contents of some text file as a single string variable.
20 rem should avoid reading an entire file at once if the file is large
20 rem should avoid reading an entire file at once if the file is large
30 rem ================================
30 rem ================================
Line 287: Line 287:
120 next
120 next
130 close 4
130 close 4
140 end</lang>
140 end</syntaxhighlight>


==={{header|BASIC256}}===
==={{header|BASIC256}}===
<lang basic256>f = freefile
<syntaxhighlight lang="basic256">f = freefile
open f, "input.txt"
open f, "input.txt"
while not eof(f)
while not eof(f)
Line 296: Line 296:
print linea$
print linea$
end while
end while
close f</lang>
close f</syntaxhighlight>


==={{header|OxygenBasic}}===
==={{header|OxygenBasic}}===
Two Formats:
Two Formats:
<lang>
<syntaxhighlight lang="text">


string s
string s
Line 310: Line 310:
Getfile "t.txt",s
Getfile "t.txt",s


</syntaxhighlight>
</lang>


==={{header|True BASIC}}===
==={{header|True BASIC}}===
<lang qbasic>OPEN #2: NAME "input.txt", ORG TEXT, ACCESS INPUT, CREATE OLD
<syntaxhighlight lang="qbasic">OPEN #2: NAME "input.txt", ORG TEXT, ACCESS INPUT, CREATE OLD
DO
DO
LINE INPUT #2: linea$
LINE INPUT #2: linea$
Line 319: Line 319:
LOOP UNTIL END #2
LOOP UNTIL END #2
CLOSE #2
CLOSE #2
END</lang>
END</syntaxhighlight>


==={{header|Yabasic}}===
==={{header|Yabasic}}===
<lang yabasic>open "input.txt" for reading as #1
<syntaxhighlight lang="yabasic">open "input.txt" for reading as #1
while not eof(1)
while not eof(1)
line input #1 linea$
line input #1 linea$
print linea$
print linea$
wend
wend
close #1</lang>
close #1</syntaxhighlight>
Or also
Or also
<lang yabasic>a = open("input.txt")
<syntaxhighlight lang="yabasic">a = open("input.txt")
while not eof(a)
while not eof(a)
line input #a linea$
line input #a linea$
print linea$
print linea$
wend</lang>
wend</syntaxhighlight>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
In [[BBC BASIC for Windows]] and [[Brandy BASIC]] the maximum string length is 65535 characters.
In [[BBC BASIC for Windows]] and [[Brandy BASIC]] the maximum string length is 65535 characters.
<lang bbcbasic> file% = OPENIN("input.txt")
<syntaxhighlight lang="bbcbasic"> file% = OPENIN("input.txt")
strvar$ = ""
strvar$ = ""
WHILE NOT EOF#file%
WHILE NOT EOF#file%
strvar$ += CHR$(BGET#file%)
strvar$ += CHR$(BGET#file%)
ENDWHILE
ENDWHILE
CLOSE #file%</lang>
CLOSE #file%</syntaxhighlight>
API version:
API version:
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> file% = OPENIN("input.txt")
<syntaxhighlight lang="bbcbasic"> file% = OPENIN("input.txt")
strvar$ = STRING$(EXT#file%, " ")
strvar$ = STRING$(EXT#file%, " ")
SYS "ReadFile", @hfile%(file%), !^strvar$, EXT#file%, ^temp%, 0
SYS "ReadFile", @hfile%(file%), !^strvar$, EXT#file%, ^temp%, 0
CLOSE #file%</lang>
CLOSE #file%</syntaxhighlight>


=={{header|Blue}}==
=={{header|Blue}}==
Line 354: Line 354:
Linux/x86-64. Reads the entire file via the mmap system call.
Linux/x86-64. Reads the entire file via the mmap system call.


<lang blue>global _start
<syntaxhighlight lang="blue">global _start


: syscall ( num:eax -- result:eax ) syscall ;
: syscall ( num:eax -- result:eax ) syscall ;
Line 401: Line 401:
bye
bye
;
;
</syntaxhighlight>
</lang>


=={{header|BQN}}==
=={{header|BQN}}==
Line 407: Line 407:
File related operations are provided under the system namespace <code>•file</code>. More can be seen under [https://mlochbaum.github.io/BQN/spec/system.html#file-access here].
File related operations are provided under the system namespace <code>•file</code>. More can be seen under [https://mlochbaum.github.io/BQN/spec/system.html#file-access here].


<lang bqn>•file.Chars "file"
<syntaxhighlight lang="bqn">•file.Chars "file"
•file.Bytes "file"
•file.Bytes "file"


Line 413: Line 413:
•FChars "file"
•FChars "file"
•FBytes "file"
•FBytes "file"
</syntaxhighlight>
</lang>


<code>•file.MapBytes</code> returns an equivalent result to <code>•file.Bytes</code>, using a memory-mapped file to load the contents on demand. It can be sliced with <code>↑</code> and <code>↓</code> to get part of the file without loading the rest. As BQN arrays are immutable, there's no way to write to the file using this result.
<code>•file.MapBytes</code> returns an equivalent result to <code>•file.Bytes</code>, using a memory-mapped file to load the contents on demand. It can be sliced with <code>↑</code> and <code>↓</code> to get part of the file without loading the rest. As BQN arrays are immutable, there's no way to write to the file using this result.
Line 422: Line 422:
=={{header|Brainf***}}==
=={{header|Brainf***}}==
While the language certainly doesn't support strings in the traditional sense, relaxing the definition to mean any contiguous sequence of null-terminated bytes permits a reasonable facsimile. This <tt>cat</tt> program eschews the simpler byte-by-byte approach (<tt>,[.,]</tt>) to demonstrate the technique.
While the language certainly doesn't support strings in the traditional sense, relaxing the definition to mean any contiguous sequence of null-terminated bytes permits a reasonable facsimile. This <tt>cat</tt> program eschews the simpler byte-by-byte approach (<tt>,[.,]</tt>) to demonstrate the technique.
<lang bf>> Keep cell 0 at 0 as a sentinel value
<syntaxhighlight lang="bf">> Keep cell 0 at 0 as a sentinel value
,[>,] Read into successive cells until EOF
,[>,] Read into successive cells until EOF
<[<] Go all the way back to the beginning
<[<] Go all the way back to the beginning
>[.>] Print successive cells while nonzero</lang>
>[.>] Print successive cells while nonzero</syntaxhighlight>
{{out}}
{{out}}
<pre>$ curl -Ls rosettacode.org | bf ">,[>,]<[<]>[.>]"
<pre>$ curl -Ls rosettacode.org | bf ">,[>,]<[<]>[.>]"
Line 434: Line 434:


=={{header|Brat}}==
=={{header|Brat}}==
<lang brat>include :file
<syntaxhighlight lang="brat">include :file


file.read file_name</lang>
file.read file_name</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
It is not possible to specify encodings: the file is read as binary data (on some system, the <tt>b</tt> flag is ignored and there's no difference between <tt>"r"</tt> and <tt>"rb"</tt>; on others, it changes the way the "new lines" are treated, but this should not affect <tt>fread</tt>)
It is not possible to specify encodings: the file is read as binary data (on some system, the <tt>b</tt> flag is ignored and there's no difference between <tt>"r"</tt> and <tt>"rb"</tt>; on others, it changes the way the "new lines" are treated, but this should not affect <tt>fread</tt>)
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>


Line 467: Line 467:
}
}
return EXIT_SUCCESS;
return EXIT_SUCCESS;
}</lang>
}</syntaxhighlight>


=== Memory map ===
=== Memory map ===
Line 474: Line 474:
We can memory-map the file.
We can memory-map the file.


<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/mman.h>
Line 502: Line 502:
close(fd);
close(fd);
return EXIT_SUCCESS;
return EXIT_SUCCESS;
}</lang>
}</syntaxhighlight>


{{works with|Windows}}
{{works with|Windows}}
Line 508: Line 508:
Memory map on Windows. See MSDN, starting with '''[https://msdn.microsoft.com/en-us/library/windows/desktop/aa366556.aspx File Mapping]'''. In practice, it would be necessary to check for errors, and to take care of large files. Also, this example is using a view on the whole file, but it's possible to create a smaller view.
Memory map on Windows. See MSDN, starting with '''[https://msdn.microsoft.com/en-us/library/windows/desktop/aa366556.aspx File Mapping]'''. In practice, it would be necessary to check for errors, and to take care of large files. Also, this example is using a view on the whole file, but it's possible to create a smaller view.


<lang c>#include <windows.h>
<syntaxhighlight lang="c">#include <windows.h>
#include <stdio.h>
#include <stdio.h>


Line 526: Line 526:
CloseHandle(hFile);
CloseHandle(hFile);
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp}}==
=={{header|C sharp}}==
{{works with|C sharp|3.0}}
{{works with|C sharp|3.0}}


<lang csharp>using System.IO;
<syntaxhighlight lang="csharp">using System.IO;


class Program
class Program
Line 540: Line 540:
// Can optionally take a second parameter to specify the encoding, e.g. File.ReadAllText("c:\\autoexec.bat", Encoding.UTF8)
// Can optionally take a second parameter to specify the encoding, e.g. File.ReadAllText("c:\\autoexec.bat", Encoding.UTF8)
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
<lang Cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <fstream>
#include <fstream>
#include <string>
#include <string>
Line 566: Line 566:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Clojure}}==
=={{header|Clojure}}==
The core function ''slurp'' does the trick; you can specify an encoding as an optional second argument:
The core function ''slurp'' does the trick; you can specify an encoding as an optional second argument:
<lang clojure>(slurp "myfile.txt")
<syntaxhighlight lang="clojure">(slurp "myfile.txt")
(slurp "my-utf8-file.txt" "UTF-8")</lang>
(slurp "my-utf8-file.txt" "UTF-8")</syntaxhighlight>


=={{header|CMake}}==
=={{header|CMake}}==
Sets a variable named ''string''.
Sets a variable named ''string''.


<lang cmake>file(READ /etc/passwd string)</lang>
<syntaxhighlight lang="cmake">file(READ /etc/passwd string)</syntaxhighlight>


This works with text files, but fails with binary files that contain NUL characters. CMake truncates the string at the first NUL character, and there is no way to detect this truncation.
This works with text files, but fails with binary files that contain NUL characters. CMake truncates the string at the first NUL character, and there is no way to detect this truncation.
Line 582: Line 582:
The only way to read binary files is to use the ''HEX'' keyword to convert the entire file to a hexadecimal string.
The only way to read binary files is to use the ''HEX'' keyword to convert the entire file to a hexadecimal string.


<lang cmake>file(READ /etc/pwd.db string HEX)</lang>
<syntaxhighlight lang="cmake">file(READ /etc/pwd.db string HEX)</syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
The following will read and store the file as a sequence of bytes.
The following will read and store the file as a sequence of bytes.


<lang lisp>(defun file-string (path)
<syntaxhighlight lang="lisp">(defun file-string (path)
(with-open-file (stream path)
(with-open-file (stream path)
(let ((data (make-string (file-length stream))))
(let ((data (make-string (file-length stream))))
(read-sequence data stream)
(read-sequence data stream)
data)))</lang>
data)))</syntaxhighlight>
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.
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.


Line 597: Line 597:
The simplest way to read an entire file to a string is by using File.read:
The simplest way to read an entire file to a string is by using File.read:


<lang ruby>content = File.read("input.txt")
<syntaxhighlight lang="ruby">content = File.read("input.txt")
puts content</lang>
puts content</syntaxhighlight>


{{out}}
{{out}}
Line 605: Line 605:
The encoding is UTF-8 by default, but it can be explicitly specified:
The encoding is UTF-8 by default, but it can be explicitly specified:


<lang ruby>content = File.read("input.txt", "UTF-16")</lang>
<syntaxhighlight lang="ruby">content = File.read("input.txt", "UTF-16")</syntaxhighlight>


or
or


<lang ruby>content = File.read("input.txt", encoding: "UTF-16")</lang>
<syntaxhighlight lang="ruby">content = File.read("input.txt", encoding: "UTF-16")</syntaxhighlight>


File.open allows for more options and closes the file implicitly. Combine it with File#gets_to_end to read the entire file:
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") do |file|
<syntaxhighlight lang="ruby">content = File.open("input.txt") do |file|
file.gets_to_end
file.gets_to_end
end</lang>
end</syntaxhighlight>


Or no implicit closing at all with File.new:
Or no implicit closing at all with File.new:


<lang ruby>file = File.new("input.txt")
<syntaxhighlight lang="ruby">file = File.new("input.txt")
content = file.gets_to_end
content = file.gets_to_end
file.close</lang>
file.close</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
<lang d>import std.file: read, readText;
<syntaxhighlight lang="d">import std.file: read, readText;


void main() {
void main() {
Line 632: Line 632:
// To read a whole file into a validated UTF-8 string:
// To read a whole file into a validated UTF-8 string:
string txt = readText("unixdict.txt");
string txt = readText("unixdict.txt");
}</lang>
}</syntaxhighlight>


=={{header|Delphi}}==
=={{header|Delphi}}==
Using TStringList
Using TStringList


<lang Delphi>program ReadAll;
<syntaxhighlight lang="delphi">program ReadAll;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 658: Line 658:
lList.Free;
lList.Free;
end;
end;
end.</lang>
end.</syntaxhighlight>




'''Works with''': Delphi 2010 and above
'''Works with''': Delphi 2010 and above


<lang Delphi>program ReadAll;
<syntaxhighlight lang="delphi">program ReadAll;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 676: Line 676:
Writeln(TFile.ReadAllText('C:\autoexec.bat', TEncoding.ASCII));
Writeln(TFile.ReadAllText('C:\autoexec.bat', TEncoding.ASCII));
Readln;
Readln;
end.</lang>
end.</syntaxhighlight>


=={{header|Déjà Vu}}==
=={{header|Déjà Vu}}==
To get a string from a file, you need to explicitly decode the binary blob that is read. Currently only UTF-8 is supported by <code>vu</code>.
To get a string from a file, you need to explicitly decode the binary blob that is read. Currently only UTF-8 is supported by <code>vu</code>.
<lang dejavu>local :filecontents !decode!utf-8 !read "file.txt"</lang>
<syntaxhighlight lang="dejavu">local :filecontents !decode!utf-8 !read "file.txt"</syntaxhighlight>


=={{header|E}}==
=={{header|E}}==


<lang e><file:foo.txt>.getText()</lang>
<syntaxhighlight lang="e"><file:foo.txt>.getText()</syntaxhighlight>


The file is assumed to be in the default encoding.
The file is assumed to be in the default encoding.

=={{header|Ecstasy}}==
A <span style="background-color: #e5e4e2"><tt>&nbsp;File&nbsp;</tt></span> object in Ecstasy has a <span style="background-color: #e5e4e2"><tt>&nbsp;contents&nbsp;</tt></span> property, which yields a <span style="background-color: #e5e4e2"><tt>&nbsp;Byte[]&nbsp;</tt></span> value:

<syntaxhighlight lang="java">
static Byte[] contentsOf(File file) {
return file.contents;
}
</syntaxhighlight>

There are also a few ways to obtain the contents of a file at compile-time as a literal instead of reading it at runtime. These examples show how a byte array literal and a string literal can be obtained from two different files, one using a relative path and one using an absolute path:

<syntaxhighlight lang="java">
Byte[] bytes = #./checkmark.ico;
String html = $/docs/website/index.htm;
</syntaxhighlight>

The compiler can even include those files as "file objects"; the files are compiled into the compiled form of the Ecstasy module by the compiler, so their contents reflect the state of those files as they were at compile time:

<syntaxhighlight lang="java">
File iconFile = ./checkmark.ico;
File htmlFile = /docs/website/index.htm;

Byte[] bytes = iconFile.contents;
String html = htmlFile.contents.unpackUtf8();
</syntaxhighlight>


=={{header|Elixir}}==
=={{header|Elixir}}==
Line 692: Line 718:
File returns a tuple: {:ok, file} is successful or {:error, reason} if unsuccessful. Errors can be caught and turned into error strings via Erlang's :file.format_error function.
File returns a tuple: {:ok, file} is successful or {:error, reason} if unsuccessful. Errors can be caught and turned into error strings via Erlang's :file.format_error function.


<syntaxhighlight lang="elixir">
<lang Elixir>
defmodule FileReader do
defmodule FileReader do
# Read in the file
# Read in the file
Line 716: Line 742:
end
end
end
end
</syntaxhighlight>
</lang>


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
<code>insert-file-contents</code> does all Emacs' usual character coding, magic file names, decompression, format decoding, etc. (<code>insert-file-contents-literally</code> can avoid that if unwanted.)
<code>insert-file-contents</code> does all Emacs' usual character coding, magic file names, decompression, format decoding, etc. (<code>insert-file-contents-literally</code> can avoid that if unwanted.)


<lang Lisp>(setq my-variable (with-temp-buffer
<syntaxhighlight lang="lisp">(setq my-variable (with-temp-buffer
(insert-file-contents "foo.txt")
(insert-file-contents "foo.txt")
(buffer-string)))</lang>
(buffer-string)))</syntaxhighlight>


(If an existing buffer is visiting the file, perhaps yet unsaved, it may be helpful to take its contents instead of re-reading the file. <code>find-buffer-visiting</code> can locate such a buffer.)
(If an existing buffer is visiting the file, perhaps yet unsaved, it may be helpful to take its contents instead of re-reading the file. <code>find-buffer-visiting</code> can locate such a buffer.)


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>{ok, B} = file:read_file("myfile.txt").</lang>
<syntaxhighlight lang="erlang">{ok, B} = file:read_file("myfile.txt").</syntaxhighlight>


This reads the entire file into a binary object.
This reads the entire file into a binary object.
Line 736: Line 762:
The openEuphoria team is/was working on supporting it. It may have been implemented by now.''
The openEuphoria team is/was working on supporting it. It may have been implemented by now.''


<lang euphoria>
<syntaxhighlight lang="euphoria">
function load_file(sequence filename)
function load_file(sequence filename)
integer fn,c
integer fn,c
Line 753: Line 779:
return data
return data
end function
end function
</syntaxhighlight>
</lang>


=={{header|F Sharp|F#}}==
=={{header|F Sharp|F#}}==
<lang fsharp>// read entire file into variable using default system encoding or with specified encoding
<syntaxhighlight lang="fsharp">// read entire file into variable using default system encoding or with specified encoding
open System.IO
open System.IO
let data = File.ReadAllText(filename)
let data = File.ReadAllText(filename)
let utf8 = File.ReadAllText(filename, System.Text.Encoding.UTF8)</lang>
let utf8 = File.ReadAllText(filename, System.Text.Encoding.UTF8)</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==


<lang factor>USING: io.encodings.ascii io.encodings.binary io.files ;
<syntaxhighlight lang="factor">USING: io.encodings.ascii io.encodings.binary io.files ;


! to read entire file as binary
! to read entire file as binary
Line 769: Line 795:


! to read entire file as lines of text
! to read entire file as lines of text
"foo.txt" ascii file-lines</lang>
"foo.txt" ascii file-lines</syntaxhighlight>


=={{header|Fantom}}==
=={{header|Fantom}}==
Provide the filename to read from as a command-line parameter.
Provide the filename to read from as a command-line parameter.
<lang fantom>
<syntaxhighlight lang="fantom">
class ReadString
class ReadString
{
{
Line 782: Line 808:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Forth}}==
=={{header|Forth}}==
{{works with|GNU Forth}}
{{works with|GNU Forth}}
<lang forth>s" foo.txt" slurp-file ( str len )</lang>
<syntaxhighlight lang="forth">s" foo.txt" slurp-file ( str len )</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
Line 792: Line 818:
Reading the entire source file in memory, then printing it. It relies on the SIZE attribute of the INQUIRE statement returning the size of the file in bytes, whereupon the ALLOCATE statement prepares a variable of the right size to receive the whole content. This SIZE facility was introduced with F2003, and prior to F90 there was no ALLOCATE facility: the size of variables was fixed at compile time.
Reading the entire source file in memory, then printing it. It relies on the SIZE attribute of the INQUIRE statement returning the size of the file in bytes, whereupon the ALLOCATE statement prepares a variable of the right size to receive the whole content. This SIZE facility was introduced with F2003, and prior to F90 there was no ALLOCATE facility: the size of variables was fixed at compile time.


<lang fortran>program read_file
<syntaxhighlight lang="fortran">program read_file
implicit none
implicit none
integer :: n
integer :: n
Line 805: Line 831:
print "(A)", s
print "(A)", s
end program</lang>
end program</syntaxhighlight>


=== Intel Fortran on Windows ===
=== Intel Fortran on Windows ===
Here is a solution using the Windows API to create a memory map of a file. It is used to print the source code of the program on the console.
Here is a solution using the Windows API to create a memory map of a file. It is used to print the source code of the program on the console.


<lang fortran>program file_win
<syntaxhighlight lang="fortran">program file_win
use kernel32
use kernel32
use iso_c_binding
use iso_c_binding
Line 831: Line 857:
s = CloseHandle(hMap)
s = CloseHandle(hMap)
s = CloseHandle(hFile)
s = CloseHandle(hFile)
end program</lang>
end program</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Open "input.txt" For Input Encoding "ascii" As #1
Open "input.txt" For Input Encoding "ascii" As #1
Line 843: Line 869:
buffer = "" '' release memory used by setting buffer to empty
buffer = "" '' release memory used by setting buffer to empty
Close #1
Close #1
Sleep</lang>
Sleep</syntaxhighlight>


=={{header|Frink}}==
=={{header|Frink}}==
The read[URL] function reads the entire contents of a URL. The encoding can be specified if necessary.
The read[URL] function reads the entire contents of a URL. The encoding can be specified if necessary.
<lang frink>
<syntaxhighlight lang="frink">
a = read["file:yourfile.txt"]
a = read["file:yourfile.txt"]
b = read["file:yourfile.txt", "UTF-8"]
b = read["file:yourfile.txt", "UTF-8"]
</syntaxhighlight>
</lang>


=={{header|FutureBasic}}==
=={{header|FutureBasic}}==
Note: This code goes beyond simply specifying the file to open. It includes a dialog window (openpanel) that allows the user to select a text file to read. Depending on system memory, as many as 4.2 billion characters can be read. The file contents are placed in a convenient scrolling textview. (Did I mention that FutureBasic -- or FB as developers prefer to call it -- is handy for Macintosh development!) Of course, the programmer is free to code his own window and menu options.
Note: This code goes beyond simply specifying the file to open. It includes a dialog window (openpanel) that allows the user to select a text file to read. Depending on system memory, as many as 4.2 billion characters can be read. The file contents are placed in a convenient scrolling textview. (Did I mention that FutureBasic -- or FB as developers prefer to call it -- is handy for Macintosh development!) Of course, the programmer is free to code his own window and menu options.
<lang futurebasic>_window = 1
<syntaxhighlight lang="futurebasic">_window = 1
begin enum 1
begin enum 1
_scrollView
_scrollView
Line 882: Line 908:
fn ReadTextFile
fn ReadTextFile


HandleEvents</lang>
HandleEvents</syntaxhighlight>


=={{header|Gambas}}==
=={{header|Gambas}}==
<lang gambas>Public Sub Form_Open()
<syntaxhighlight lang="gambas">Public Sub Form_Open()
Dim sFile As String
Dim sFile As String


sFile = File.Load(User.home &/ "file.txt")
sFile = File.Load(User.home &/ "file.txt")


End</lang>
End</syntaxhighlight>


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap>InputTextFile("input.txt");
<syntaxhighlight lang="gap">InputTextFile("input.txt");
s := ReadAll(f);; # two semicolons to hide the result, which may be long
s := ReadAll(f);; # two semicolons to hide the result, which may be long
CloseStream(f);</lang>
CloseStream(f);</syntaxhighlight>


=={{header|Genie}}==
=={{header|Genie}}==
<lang genie>[indent=4]
<syntaxhighlight lang="genie">[indent=4]
/*
/*
Read entire file, in Genie
Read entire file, in Genie
Line 918: Line 944:
return
return


stdout.printf("%d bytes read from %s\n", fileContents.length, fileName)</lang>
stdout.printf("%d bytes read from %s\n", fileContents.length, fileName)</syntaxhighlight>


{{out}}
{{out}}
Line 934: Line 960:
The conversion in the next line from byte array to string also makes no changes to the data.
The conversion in the next line from byte array to string also makes no changes to the data.
In the example below <tt>sv</tt> will have an exact copy of the data in the file, without regard to encoding.
In the example below <tt>sv</tt> will have an exact copy of the data in the file, without regard to encoding.
<lang go>import "io/ioutil"
<syntaxhighlight lang="go">import "io/ioutil"


data, err := ioutil.ReadFile(filename)
data, err := ioutil.ReadFile(filename)
sv := string(data)</lang>
sv := string(data)</syntaxhighlight>
Go also supports memory mapped files on OSes with a mmap syscall (e.g. Unix-like).
Go also supports memory mapped files on OSes with a mmap syscall (e.g. Unix-like).
The following prints the contents of "file".
The following prints the contents of "file".
(The included "build constraint" prevents this from being compiled on architectures known to lack <tt>syscall.Mmap</tt>, another source file with the opposite build constraint could use <tt>ioutil.ReadFile</tt> as above).
(The included "build constraint" prevents this from being compiled on architectures known to lack <tt>syscall.Mmap</tt>, another source file with the opposite build constraint could use <tt>ioutil.ReadFile</tt> as above).
<lang go>// +build !windows,!plan9,!nacl // These lack syscall.Mmap
<syntaxhighlight lang="go">// +build !windows,!plan9,!nacl // These lack syscall.Mmap


package main
package main
Line 967: Line 993:
}
}
fmt.Println(string(data))
fmt.Println(string(data))
}</lang>
}</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
<lang groovy>def fileContent = new File("c:\\file.txt").text</lang>
<syntaxhighlight lang="groovy">def fileContent = new File("c:\\file.txt").text</syntaxhighlight>


=={{header|GUISS}}==
=={{header|GUISS}}==


<lang guiss>Start,Programs,Accessories,Notepad,Menu:File,Open,Doubleclick:Icon:Notes.TXT,Button:OK</lang>
<syntaxhighlight lang="guiss">Start,Programs,Accessories,Notepad,Menu:File,Open,Doubleclick:Icon:Notes.TXT,Button:OK</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
In the IO monad:
In the IO monad:


<lang haskell>do text <- readFile filepath
<syntaxhighlight lang="haskell">do text <- readFile filepath
-- do stuff with text</lang>
-- do stuff with text</syntaxhighlight>


Note that <code>readFile</code> is lazy. If you want to ensure the entire file is read in at once, before any other IO actions are run, try:
Note that <code>readFile</code> is lazy. If you want to ensure the entire file is read in at once, before any other IO actions are run, try:


<lang haskell>eagerReadFile :: FilePath -> IO String
<syntaxhighlight lang="haskell">eagerReadFile :: FilePath -> IO String
eagerReadFile filepath = do
eagerReadFile filepath = do
text <- readFile filepath
text <- readFile filepath
last text `seq` return text</lang>
last text `seq` return text</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
The first code snippet below reads from stdin directly into the string fs,
The first code snippet below reads from stdin directly into the string fs,
preserving line separators (if any) and reading in large chunks.
preserving line separators (if any) and reading in large chunks.
<lang Icon>every (fs := "") ||:= |reads(1000000)</lang>
<syntaxhighlight lang="icon">every (fs := "") ||:= |reads(1000000)</syntaxhighlight>
The second code snippet below performs the same operation using an intermediate list fL and applying a function (e.g. FUNC) to each line. Use this form when you need to perform additional string functions such as 'trim' or 'map' on each line. This avoids unnecessary garbage collections which will occur with larger files. The list can be discarded when done. Line separators are mapped into newlines.
The second code snippet below performs the same operation using an intermediate list fL and applying a function (e.g. FUNC) to each line. Use this form when you need to perform additional string functions such as 'trim' or 'map' on each line. This avoids unnecessary garbage collections which will occur with larger files. The list can be discarded when done. Line separators are mapped into newlines.
<lang Icon>every put(fL := [],|FUNC(read()))
<syntaxhighlight lang="icon">every put(fL := [],|FUNC(read()))
every (fs := "") ||:= !fL || "\n"
every (fs := "") ||:= !fL || "\n"
fL := &null</lang>
fL := &null</syntaxhighlight>


=={{header|Inform 7}}==
=={{header|Inform 7}}==
Line 1,002: Line 1,028:


{{works with|Glulx virtual machine}}
{{works with|Glulx virtual machine}}
<lang inform7>Home is a room.
<syntaxhighlight lang="inform7">Home is a room.


The File of Testing is called "test".
The File of Testing is called "test".
Line 1,008: Line 1,034:
When play begins:
When play begins:
say "[text of the File of Testing]";
say "[text of the File of Testing]";
end the story.</lang>
end the story.</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==


<lang j> require 'files' NB. not needed for J7 & later
<syntaxhighlight lang="j"> require 'files' NB. not needed for J7 & later
var=: freads 'foo.txt'</lang>
var=: fread 'foo.txt'</syntaxhighlight>


To memory map the file:
To memory map the file:


<lang j> require 'jmf'
<syntaxhighlight lang="j"> require 'jmf'
JCHAR map_jmf_ 'var';'foo.txt'</lang>
JCHAR map_jmf_ 'var';'foo.txt'</syntaxhighlight>


Caution: updating the value of the memory mapped variable will update the file, and this characteristic remains when the variable's value is passed, unmodified, to a verb which modifies its own local variables.
Caution: updating the value of the memory mapped variable will update the file, and this characteristic remains when the variable's value is passed, unmodified, to a verb which modifies its own local variables.

=={{header|Jakt}}==
<syntaxhighlight lang="jakt">
fn main() {
let filename = "Read_entire_file.jakt"
mut file = File::open_for_reading(filename)
mut builder = StringBuilder::create()
for byte in file.read_all() {
builder.append(byte)
}
let contents = builder.to_string()
println("{}", contents)
}
</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
There is no single method to do this in Java 6 and below (probably because reading an entire file at once could fill up your memory quickly), so to do this you could simply append the contents as you read them into a buffer.
There is no single method to do this in Java 6 and below (probably because reading an entire file at once could fill up your memory quickly), so to do this you could simply append the contents as you read them into a buffer.
<lang java>import java.io.BufferedReader;
<syntaxhighlight lang="java">import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.IOException;
Line 1,045: Line 1,085:
return contents.toString();
return contents.toString();
}
}
}</lang>
}</syntaxhighlight>


One can memory-map the file in Java, but there's little to gain if one is to create a String out of the file:
One can memory-map the file in Java, but there's little to gain if one is to create a String out of the file:


<lang java>
<syntaxhighlight lang="java">
import java.nio.channels.FileChannel.MapMode;
import java.nio.channels.FileChannel.MapMode;
import java.nio.MappedByteBuffer;
import java.nio.MappedByteBuffer;
Line 1,069: Line 1,109:
return buffer;
return buffer;
}
}
}</lang>
}</syntaxhighlight>


or one can take a shortcut:
or one can take a shortcut:
<lang java>String content = new Scanner(new File("foo"), "UTF-8").useDelimiter("\\A").next();</lang>
<syntaxhighlight lang="java">String content = new Scanner(new File("foo"), "UTF-8").useDelimiter("\\A").next();</syntaxhighlight>
this works because Scanner will search the file for a delimiter and return everything before that. <code>\A</code> is the beginning of the file, which it will never find until the end of the file is reached.
this works because Scanner will search the file for a delimiter and return everything before that. <code>\A</code> is the beginning of the file, which it will never find until the end of the file is reached.


{{works with|Java|7+}}
{{works with|Java|7+}}
Java 7 added <code>java.nio.file.Files</code> which has two methods for accomplishing this task: <code>Files.readAllLines</code> and <code>Files.readAllBytes</code>:
Java 7 added <code>java.nio.file.Files</code> which has two methods for accomplishing this task: <code>Files.readAllLines</code> and <code>Files.readAllBytes</code>:
<lang java5>import java.util.List;
<syntaxhighlight lang="java5">import java.util.List;
import java.nio.charset.Charset;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.nio.file.*;
Line 1,091: Line 1,131:
return Files.readAllBytes(file);
return Files.readAllBytes(file);
}
}
}</lang>
}</syntaxhighlight>

{{works with|Java|11+}}
Java 11 added the method <code>readString</code>:

<syntaxhighlight lang="java">
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

public class ReadAll {
public static void main(String[] args) {
System.out.print(Files.readString(Path.of(args[0], StandardCharsets.UTF_8)));
}
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
This works in IExplorer or a standalone js file. Note the similarity to the VBScript code.
This works in IExplorer or a standalone js file. Note the similarity to the VBScript code.
<lang javascript>var fso=new ActiveXObject("Scripting.FileSystemObject");
<syntaxhighlight lang="javascript">var fso=new ActiveXObject("Scripting.FileSystemObject");
var f=fso.OpenTextFile("c:\\myfile.txt",1);
var f=fso.OpenTextFile("c:\\myfile.txt",1);
var s=f.ReadAll();
var s=f.ReadAll();
f.Close();
f.Close();
try{alert(s)}catch(e){WScript.Echo(s)}</lang>
try{alert(s)}catch(e){WScript.Echo(s)}</syntaxhighlight>


The following works in all browsers, including IE10.
The following works in all browsers, including IE10.
<lang javascript>var file = document.getElementById("fileInput").files.item(0); //a file input element
<syntaxhighlight lang="javascript">var file = document.getElementById("fileInput").files.item(0); //a file input element
if (file) {
if (file) {
var reader = new FileReader();
var reader = new FileReader();
Line 1,116: Line 1,169:
alert(event);
alert(event);
}
}
</syntaxhighlight>
</lang>


=={{header|jq}}==
=={{header|jq}}==
The . filter will read in a file of raw text, e.g. if the file is named input.txt and we wanted to emit it as a single JSON string:
The . filter will read in a file of raw text, e.g. if the file is named input.txt and we wanted to emit it as a single JSON string:
<lang sh>jq -R -s . input.txt</lang>
<syntaxhighlight lang="sh">jq -R -s . input.txt</syntaxhighlight>
In practice, this is probably not very useful. It would be more typical to collect the raw lines into an array of JSON strings.
In practice, this is probably not very useful. It would be more typical to collect the raw lines into an array of JSON strings.


If it is known that the lines are delimited by a single "newline" character, then one could simply pipe from one jq command to another:<lang sh>jq -R . input.txt | jq -s .</lang>
If it is known that the lines are delimited by a single "newline" character, then one could simply pipe from one jq command to another:<syntaxhighlight lang="sh">jq -R . input.txt | jq -s .</syntaxhighlight>
Equivalently:<lang sh>jq -R -s 'split("\n")' input.txt </lang>
Equivalently:<syntaxhighlight lang="sh">jq -R -s 'split("\n")' input.txt </syntaxhighlight>


Other cases can be similarly handled.
Other cases can be similarly handled.


=={{header|Jsish}}==
=={{header|Jsish}}==
<lang javascript>var contents = File.read("filename")</lang>
<syntaxhighlight lang="javascript">var contents = File.read("filename")</syntaxhighlight>


From the shell:
From the shell:
Line 1,148: Line 1,201:
=={{header|Julia}}==
=={{header|Julia}}==
The built-in function <code>read</code>, when used with a second argument of String, reads the whole file named by its first argument into a string (assuming UTF8 encoding).
The built-in function <code>read</code>, when used with a second argument of String, reads the whole file named by its first argument into a string (assuming UTF8 encoding).
<lang Julia>read("/devel/myfile.txt", String) # read file into a string</lang>
<syntaxhighlight lang="julia">read("/devel/myfile.txt", String) # read file into a string</syntaxhighlight>
Alternatively, for files that are too large to read into memory without swapping, there are a variety of ways to memory-map the file, for example as an array of bytes:
Alternatively, for files that are too large to read into memory without swapping, there are a variety of ways to memory-map the file, for example as an array of bytes:
<lang Julia>A = Mmap.mmap(open("/devel/myfile.txt"), Array{UInt8,1})</lang>
<syntaxhighlight lang="julia">A = Mmap.mmap(open("/devel/myfile.txt"), Array{UInt8,1})</syntaxhighlight>

=={{header|K}}==
{{works with|ngn/k}}<syntaxhighlight lang=K>`c$1:"example.txt"</syntaxhighlight>


The following might be more idiomatic, but returns a list of strings, corresponding to the lines of the file, rather than a single string.
<syntaxhighlight lang=K>0:"example.txt"</syntaxhighlight>
=={{header|KAP}}==
=={{header|KAP}}==


The built-in function <code>io:readFile</code> will read the entire content of the file as a string:
The built-in function <code>io:readFile</code> will read the entire content of the file as a string:


<lang kap>content ← io:readFile "file.txt"</lang>
<syntaxhighlight lang="kap">content ← io:readFile "file.txt"</syntaxhighlight>


The function <code>io:read</code> can be used to return all the lines in the file as an array:
The function <code>io:read</code> can be used to return all the lines in the file as an array:


<lang kap>content ← io:read "file.txt"</lang>
<syntaxhighlight lang="kap">content ← io:read "file.txt"</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>import java.io.File
<syntaxhighlight lang="scala">import java.io.File


fun main(args: Array<String>) {
fun main(args: Array<String>) {
println(File("unixdict.txt").readText(charset = Charsets.UTF_8))
println(File("unixdict.txt").readText(charset = Charsets.UTF_8))
}</lang>
}</syntaxhighlight>


=={{header|LabVIEW}}==
=={{header|LabVIEW}}==
Line 1,173: Line 1,231:


=={{header|Lang5}}==
=={{header|Lang5}}==
<lang lang5>'foo.txt slurp</lang>
<syntaxhighlight lang="lang5">'foo.txt slurp</syntaxhighlight>


=={{header|Lasso}}==
=={{header|Lasso}}==
By default, string objects, which are always Unicode, are created with the assumption that the file contains UTF-8 encoded data. This assumption can be changed by settings the file objects’s character encoding value. When reading the data as a bytes object, the unaltered file data is returned.
By default, string objects, which are always Unicode, are created with the assumption that the file contains UTF-8 encoded data. This assumption can be changed by settings the file objects’s character encoding value. When reading the data as a bytes object, the unaltered file data is returned.


<lang Lasso >local(f) = file('foo.txt')
<syntaxhighlight lang="lasso ">local(f) = file('foo.txt')
#f->readString</lang>
#f->readString</syntaxhighlight>


=={{header|LFE}}==
=={{header|LFE}}==


<lang lisp>
<syntaxhighlight lang="lisp">
(set `#(ok ,data) (file:read_file "myfile.txt"))
(set `#(ok ,data) (file:read_file "myfile.txt"))
</syntaxhighlight>
</lang>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<lang lb>filedialog "Open a Text File","*.txt",file$
<syntaxhighlight lang="lb">filedialog "Open a Text File","*.txt",file$
if file$<>"" then
if file$<>"" then
open file$ for input as #1
open file$ for input as #1
Line 1,194: Line 1,252:
close #1
close #1
print entire$
print entire$
end if</lang>
end if</syntaxhighlight>


=={{header|Lingo}}==
=={{header|Lingo}}==
<lang lingo>----------------------------------------
<syntaxhighlight lang="lingo">----------------------------------------
-- Reads whole file, returns string
-- Reads whole file, returns string
-- @param {string} tFile
-- @param {string} tFile
Line 1,209: Line 1,267:
fp.closeFile()
fp.closeFile()
return res
return res
end</lang>
end</syntaxhighlight>


=={{header|LiveCode}}==
=={{header|LiveCode}}==
Line 1,216: Line 1,274:


Using URL
Using URL
<lang LiveCode>put URL "file:///usr/share/dict/words" into tVar
<syntaxhighlight lang="livecode">put URL "file:///usr/share/dict/words" into tVar
put the number of lines of tVar</lang>
put the number of lines of tVar</syntaxhighlight>


Using file open + read + close
Using file open + read + close
<lang LiveCode>local tFile,tLinecount
<syntaxhighlight lang="livecode">local tFile,tLinecount
put "/usr/share/dict/words" into tFile
put "/usr/share/dict/words" into tFile
open file tFile for text read
open file tFile for text read
read from file tFile until EOF
read from file tFile until EOF
put the number of lines of it -- file contents held in "it" variable
put the number of lines of it -- file contents held in "it" variable
close file tFile</lang>
close file tFile</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<syntaxhighlight lang="lua">
<lang Lua>
--If the file opens with no problems, io.open will return a
--If the file opens with no problems, io.open will return a
--handle to the file with methods attached.
--handle to the file with methods attached.
Line 1,250: Line 1,308:
--garbage collected.
--garbage collected.
file:close()
file:close()
</syntaxhighlight>
</lang>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module checkit {
Module checkit {
\\ prepare a file
\\ prepare a file
Line 1,274: Line 1,332:
}
}
checkit
checkit
</syntaxhighlight>
</lang>


=={{header|M4}}==
=={{header|M4}}==
An approximation to file reading can be had by <code>include()</code> which reads a file as M4 input. If it's inside a <code>define()</code> then the input is captured as a definition. But this is extremely limited since any macro names, parens, commas, quote characters etc in the file will expand and upset the capture.
An approximation to file reading can be had by <code>include()</code> which reads a file as M4 input. If it's inside a <code>define()</code> then the input is captured as a definition. But this is extremely limited since any macro names, parens, commas, quote characters etc in the file will expand and upset the capture.


<lang m4>define(`foo',include(`file.txt'))
<syntaxhighlight lang="m4">define(`foo',include(`file.txt'))
defn(`foo')
defn(`foo')
defn(`foo')</lang>
defn(`foo')</syntaxhighlight>


=={{header|Make}}==
=={{header|Make}}==
{{works with|GNU make}}
{{works with|GNU make}}
<lang Make>contents := $(shell cat foo.txt)</lang>
<syntaxhighlight lang="make">contents := $(shell cat foo.txt)</syntaxhighlight>
This is [http://www.gnu.org/software/make/manual/html_node/Shell-Function.html from the GNU Make manual]. As noted there, newlines are converted to spaces in the <code>$(contents)</code> variable. This might be acceptable for files which are a list of words anyway.
This is [http://www.gnu.org/software/make/manual/html_node/Shell-Function.html from the GNU Make manual]. As noted there, newlines are converted to spaces in the <code>$(contents)</code> variable. This might be acceptable for files which are a list of words anyway.


=={{header|Maple}}==
=={{header|Maple}}==
First solution:
First solution:
<syntaxhighlight lang="maple">
<lang Maple>
s1 := readbytes( "file1.txt", infinity, TEXT ):
s1 := readbytes( "file1.txt", infinity, TEXT ):
</syntaxhighlight>
</lang>
Second solution:
Second solution:
<syntaxhighlight lang="maple">
<lang Maple>
s2 := FileTools:-Text:-ReadFile( "file2.txt" ):
s2 := FileTools:-Text:-ReadFile( "file2.txt" ):
</syntaxhighlight>
</lang>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>Import["filename","String"]</lang>
<syntaxhighlight lang="mathematica">Import["filename","String"]</syntaxhighlight>


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
<lang MATLAB> fid = fopen('filename','r');
<syntaxhighlight lang="matlab"> fid = fopen('filename','r');
[str,count] = fread(fid, [1,inf], 'uint8=>char'); % s will be a character array, count has the number of bytes
[str,count] = fread(fid, [1,inf], 'uint8=>char'); % s will be a character array, count has the number of bytes
fclose(fid); </lang>
fclose(fid); </syntaxhighlight>


=={{header|Mercury}}==
=={{header|Mercury}}==
<lang Mercury>:- module read_entire_file.
<syntaxhighlight lang="mercury">:- module read_entire_file.
:- interface.
:- interface.


Line 1,333: Line 1,391:
io.stderr_stream(Stderr, !IO),
io.stderr_stream(Stderr, !IO),
io.write_string(Stderr, io.error_message(IO_Error) ++ "\n", !IO)
io.write_string(Stderr, io.error_message(IO_Error) ++ "\n", !IO)
).</lang>
).</syntaxhighlight>


=={{header|Microsoft Small Basic}}==
=={{header|Microsoft Small Basic}}==
<lang smallbasic> v=File.ReadContents(filename) </lang>
<syntaxhighlight lang="smallbasic"> v=File.ReadContents(filename) </syntaxhighlight>


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
<lang Nanoquery>import Nanoquery.IO
<syntaxhighlight lang="nanoquery">import Nanoquery.IO
contents = new(File, "example.txt").readAll()</lang>
contents = new(File, "example.txt").readAll()</syntaxhighlight>


=={{header|Neko}}==
=={{header|Neko}}==
<syntaxhighlight lang="actionscript">/**
<lang ActionScript>/**
Read entire file
Read entire file
Tectonics:
Tectonics:
Line 1,357: Line 1,415:
} catch e {
} catch e {
$print("Exception: ", e, "\n");
$print("Exception: ", e, "\n");
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,365: Line 1,423:


=={{header|NetRexx}}==
=={{header|NetRexx}}==
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary


Line 1,408: Line 1,466:


return slurped
return slurped
</syntaxhighlight>
</lang>


=={{header|NewLISP}}==
=={{header|NewLISP}}==
<lang NewLISP>(read-file "filename")</lang>
<syntaxhighlight lang="newlisp">(read-file "filename")</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
To read the content of a file specified by its name:
To read the content of a file specified by its name:
<lang Nim>readFile(filename)</lang>
<syntaxhighlight lang="nim">readFile(filename)</syntaxhighlight>
To read the contents of an opened file:
To read the contents of an opened file:
<lang>readAll(f)</lang>
<syntaxhighlight lang="text">readAll(f)</syntaxhighlight>


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>
<syntaxhighlight lang="objeck">
string := FileReader->ReadFile("in.txt");
string := FileReader->ReadFile("in.txt");
</syntaxhighlight>
</lang>


=={{header|Objective-C}}==
=={{header|Objective-C}}==
<lang objc>
<syntaxhighlight lang="objc">
/*** 0. PREPARATION */
/*** 0. PREPARATION */
// We need a text file to read; let's redirect a C string to a new file
// We need a text file to read; let's redirect a C string to a new file
Line 1,458: Line 1,516:
NSLog(@"%@", aString);
NSLog(@"%@", aString);
}
}
</syntaxhighlight>
</lang>


=={{header|OCaml}}==
=={{header|OCaml}}==
Line 1,464: Line 1,522:
For most uses we can use this function:
For most uses we can use this function:


<lang ocaml>let load_file f =
<syntaxhighlight lang="ocaml">let load_file f =
let ic = open_in f in
let ic = open_in f in
let n = in_channel_length ic in
let n = in_channel_length ic in
Line 1,470: Line 1,528:
really_input ic s 0 n;
really_input ic s 0 n;
close_in ic;
close_in ic;
(s)</lang>
(s)</syntaxhighlight>


We can replace the last line with the one below if we want to return a type <code>string</code> instead of <code>bytes</code>:
We can replace the last line with the one below if we want to return a type <code>string</code> instead of <code>bytes</code>:
<lang ocaml> (Bytes.unsafe_to_string s)</lang>
<syntaxhighlight lang="ocaml"> (Bytes.unsafe_to_string s)</syntaxhighlight>


There is no problem reading an entire file with the function <code>really_input</code> because this function is implemented appropriately with an internal loop, but it can only load files which size is equal or inferior to the maximum length of an ocaml string. This maximum size is available with the variable <code>Sys.max_string_length</code>. On 32 bit machines this size is about 16Mo.
There is no problem reading an entire file with the function <code>really_input</code> because this function is implemented appropriately with an internal loop, but it can only load files which size is equal or inferior to the maximum length of an ocaml string. This maximum size is available with the variable <code>Sys.max_string_length</code>. On 32 bit machines this size is about 16Mo.
Line 1,479: Line 1,537:
To load bigger files several solutions exist, for example create a structure that contains several strings where the contents of the file can be split. Or another solution that is often used is to use a bigarray of chars instead of a string:
To load bigger files several solutions exist, for example create a structure that contains several strings where the contents of the file can be split. Or another solution that is often used is to use a bigarray of chars instead of a string:


<lang ocaml>type big_string =
<syntaxhighlight lang="ocaml">type big_string =
(char, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t</lang>
(char, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t</syntaxhighlight>


The function below returns the contents of a file with this type <code>big_string</code>, and it does so with "memory-mapping":
The function below returns the contents of a file with this type <code>big_string</code>, and it does so with "memory-mapping":


<lang ocaml>let load_big_file filename =
<syntaxhighlight lang="ocaml">let load_big_file filename =
let fd = Unix.openfile filename [Unix.O_RDONLY] 0o640 in
let fd = Unix.openfile filename [Unix.O_RDONLY] 0o640 in
let len = Unix.lseek fd 0 Unix.SEEK_END in
let len = Unix.lseek fd 0 Unix.SEEK_END in
Line 1,492: Line 1,550:
Bigarray.char Bigarray.c_layout shared len in
Bigarray.char Bigarray.c_layout shared len in
Unix.close fd;
Unix.close fd;
(bstr)</lang>
(bstr)</syntaxhighlight>


Then the length of the data can be get with <code>Bigarray.Array1.dim</code> instead of <code>String.length</code>, and we can access to a given char with the syntactic sugar <code>bstr.{i}</code> (instead of <code>str.[i]</code>) as shown in the small piece of code below (similar to the cat command):
Then the length of the data can be get with <code>Bigarray.Array1.dim</code> instead of <code>String.length</code>, and we can access to a given char with the syntactic sugar <code>bstr.{i}</code> (instead of <code>str.[i]</code>) as shown in the small piece of code below (similar to the cat command):


<lang ocaml>let () =
<syntaxhighlight lang="ocaml">let () =
let bstr = load_big_file Sys.argv.(1) in
let bstr = load_big_file Sys.argv.(1) in
let len = Bigarray.Array1.dim bstr in
let len = Bigarray.Array1.dim bstr in
Line 1,502: Line 1,560:
let c = bstr.{i} in
let c = bstr.{i} in
print_char c
print_char c
done</lang>
done</syntaxhighlight>


=={{header|Ol}}==
=={{header|Odin}}==
<lang scheme>
(define content (bytes->string
(vec-iter
(file->vector "file.txt"))))


<syntaxhighlight lang="odin">package main
(print content)

</lang>
import "core:os"
import "core:fmt"

main :: proc() {
data, ok := os.read_entire_file("input.txt")
assert(ok, "Could not open file")
defer delete(data)

fmt.print(string(data))
}</syntaxhighlight>

=={{header|Ol}}==
<syntaxhighlight lang="scheme">
(file->string "filename")
</syntaxhighlight>


=={{header|ooRexx}}==
=={{header|ooRexx}}==
===version 1===
===version 1===
<lang ooRexx>file = 'c:\test.txt'
<syntaxhighlight lang="oorexx">file = 'c:\test.txt'
myStream = .stream~new(file)
myStream = .stream~new(file)
myString = myStream~charIn(,myStream~chars)</lang>
myString = myStream~charIn(,myStream~chars)</syntaxhighlight>


Streams are opened on demand and closed when the script finishes.
Streams are opened on demand and closed when the script finishes.
It is possible if you wish to open and close the streams explicitly
It is possible if you wish to open and close the streams explicitly


<lang ooRexx>file = 'c:\test.txt'
<syntaxhighlight lang="oorexx">file = 'c:\test.txt'
myStream = .stream~new(file)
myStream = .stream~new(file)
if mystream~open('read') = 'READY:'
if mystream~open('read') = 'READY:'
Line 1,528: Line 1,597:
myString = myStream~charIn(,myStream~chars)
myString = myStream~charIn(,myStream~chars)
myStream~close
myStream~close
end</lang>
end</syntaxhighlight>


===version 2 EXECIO===
===version 2 EXECIO===
One can also use EXECIO as it is known from VM/CMS and MVS/TSO:
One can also use EXECIO as it is known from VM/CMS and MVS/TSO:
<lang rexx>address hostemu 'execio * diskr "./st.in" (finis stem in.'
<syntaxhighlight lang="rexx">address hostemu 'execio * diskr "./st.in" (finis stem in.'
Say in.0 'lines in file st.in'
Say in.0 'lines in file st.in'
v=''
v=''
Line 1,540: Line 1,609:
End
End
say 'v='v
say 'v='v
::requires "hostemu" LIBRARY </lang>
::requires "hostemu" LIBRARY </syntaxhighlight>
{{out}}
{{out}}
<pre>E:\>rexx ref
<pre>E:\>rexx ref
Line 1,556: Line 1,625:
=={{header|Oz}}==
=={{header|Oz}}==
The interface for file operations is object-oriented.
The interface for file operations is object-oriented.
<lang oz>declare
<syntaxhighlight lang="oz">declare
FileHandle = {New Open.file init(name:"test.txt")}
FileHandle = {New Open.file init(name:"test.txt")}
FileContents = {FileHandle read(size:all list:$)}
FileContents = {FileHandle read(size:all list:$)}
in
in
{FileHandle close}
{FileHandle close}
{System.printInfo FileContents}</lang>
{System.printInfo FileContents}</syntaxhighlight>
<code>FileContents</code> is a list of bytes. The operation does not assume any particular encoding.
<code>FileContents</code> is a list of bytes. The operation does not assume any particular encoding.


=={{header|Panda}}==
=={{header|Panda}}==
It returns a unicode string of type 'text'.
It returns a unicode string of type 'text'.
<lang panda>file:readme.txt .text</lang>
<syntaxhighlight lang="panda">file:readme.txt .text</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
Line 1,573: Line 1,642:
<code>readstr()</code> returns a vector of strings which are the file lines, without newlines. They can be concatenated to make a single string.
<code>readstr()</code> returns a vector of strings which are the file lines, without newlines. They can be concatenated to make a single string.


<lang parigp>str = concat(apply(s->concat(s,"\n"), readstr("file.txt")))</lang>
<syntaxhighlight lang="parigp">str = concat(apply(s->concat(s,"\n"), readstr("file.txt")))</syntaxhighlight>


Since <code>readstr()</code> returns strings without newlines there's no way to tell whether the last line had a newline or not. This is fine for its intended use on text files, but not good for reading binary files.
Since <code>readstr()</code> returns strings without newlines there's no way to tell whether the last line had a newline or not. This is fine for its intended use on text files, but not good for reading binary files.
Line 1,584: Line 1,653:
The modern recommended way, is using one of these CPAN modules:
The modern recommended way, is using one of these CPAN modules:


* <lang perl>use File::Slurper 'read_text';
* <syntaxhighlight lang="perl">use File::Slurper 'read_text';
my $text = read_text($filename, $data);</lang>
my $text = read_text($filename, $data);</syntaxhighlight>
* <lang perl>use Path::Tiny;
* <syntaxhighlight lang="perl">use Path::Tiny;
my $text = path($filename)->slurp_utf8;</lang>
my $text = path($filename)->slurp_utf8;</syntaxhighlight>
* <lang perl>use IO::All;
* <syntaxhighlight lang="perl">use IO::All;
$text = io($filename)->utf8->all;</lang>
$text = io($filename)->utf8->all;</syntaxhighlight>


Traditional ways, without CPAN modules:
Traditional ways, without CPAN modules:


* <lang perl>open my $fh, '<:encoding(UTF-8)', $filename or die "Could not open '$filename': $!";
* <syntaxhighlight lang="perl">open my $fh, '<:encoding(UTF-8)', $filename or die "Could not open '$filename': $!";
my $text;
my $text;
read $fh, $text, -s $filename;
read $fh, $text, -s $filename;
close $fh;</lang>
close $fh;</syntaxhighlight>
*<lang perl>my $text;
*<syntaxhighlight lang="perl">my $text;
{
{
local $/ = undef;
local $/ = undef;
Line 1,603: Line 1,672:
$text = <$fh>;
$text = <$fh>;
close $fh;
close $fh;
}</lang>
}</syntaxhighlight>
* <lang perl>my $text = do { local( @ARGV, $/ ) = ( $filename ); <> };</lang>
* <syntaxhighlight lang="perl">my $text = do { local( @ARGV, $/ ) = ( $filename ); <> };</syntaxhighlight>


For a one-liner from shell, use <code>-0[code]</code>. It normally specifies the oct char code of record separator (<code>$/</code>), so for example <code>perl -n -040</code> would read chunks of text ending at each space (<code>$/ = ' '</code>). However, <code>-0777</code> has special meaning: <code>$/ = undef</code>, so the whole file is read in at once (<code>chr 0777</code> happens to be "ǿ", but Larry doesn't think one should use that as record separator).
For a one-liner from shell, use <code>-0[code]</code>. It normally specifies the oct char code of record separator (<code>$/</code>), so for example <code>perl -n -040</code> would read chunks of text ending at each space (<code>$/ = ' '</code>). However, <code>-0777</code> has special meaning: <code>$/ = undef</code>, so the whole file is read in at once (<code>chr 0777</code> happens to be "ǿ", but Larry doesn't think one should use that as record separator).
<lang perl>perl -n -0777 -e 'print "file len: ".length' stuff.txt</lang>
<syntaxhighlight lang="perl">perl -n -0777 -e 'print "file len: ".length' stuff.txt</syntaxhighlight>


===Memory-mapping===
===Memory-mapping===
<lang Perl>use File::Map 'map_file';
<syntaxhighlight lang="perl">use File::Map 'map_file';
map_file(my $str, "foo.txt");
map_file(my $str, "foo.txt");
print $str;</lang>
print $str;</syntaxhighlight>


<lang Perl>use Sys::Mmap;
<syntaxhighlight lang="perl">use Sys::Mmap;
Sys::Mmap->new(my $str, 0, 'foo.txt')
Sys::Mmap->new(my $str, 0, 'foo.txt')
or die "Cannot Sys::Mmap->new: $!";
or die "Cannot Sys::Mmap->new: $!";
print $str;</lang>
print $str;</syntaxhighlight>


<code>File::Map</code> has the advantage of not requiring an explicit <code>munmap()</code>. Its tie is faster than the tie form of <code>Sys::Mmap</code> too.
<code>File::Map</code> has the advantage of not requiring an explicit <code>munmap()</code>. Its tie is faster than the tie form of <code>Sys::Mmap</code> too.
Line 1,623: Line 1,692:
=={{header|Phix}}==
=={{header|Phix}}==
{{libheader|Phix/basics}}
{{libheader|Phix/basics}}
<!--<lang Phix>(notonline)-->
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">get_text</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">command_line</span><span style="color: #0000FF;">()[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">])</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">get_text</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">command_line</span><span style="color: #0000FF;">()[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">])</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 1,635: Line 1,704:
=={{header|PHP}}==
=={{header|PHP}}==
Read as string
Read as string
<lang php>file_get_contents($filename)</lang>
<syntaxhighlight lang="php">file_get_contents($filename)</syntaxhighlight>
Read as array, one element per line
Read as array, one element per line
<lang php>file($filename)</lang>
<syntaxhighlight lang="php">file($filename)</syntaxhighlight>


=={{header|Picat}}==
=={{header|Picat}}==
Line 1,643: Line 1,712:


{{works with|Picat}}
{{works with|Picat}}
<syntaxhighlight lang="picat">
<lang Picat>
main(Args) =>
main(Args) =>
File = Args[1],
File = Args[1],
String = read_file_chars(File).
String = read_file_chars(File).
</syntaxhighlight>
</lang>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
Using '[http://software-lab.de/doc/refT.html#till till]' is the shortest way:
Using '[http://software-lab.de/doc/refT.html#till till]' is the shortest way:
<lang PicoLisp>(in "file" (till NIL T))</lang>
<syntaxhighlight lang="picolisp">(in "file" (till NIL T))</syntaxhighlight>
To read the file into a list of characters:
To read the file into a list of characters:
<lang PicoLisp>(in "file" (till NIL))</lang>
<syntaxhighlight lang="picolisp">(in "file" (till NIL))</syntaxhighlight>
or, more explicit:
or, more explicit:
<lang PicoLisp>(in "file" (make (while (char) (link @))))</lang>
<syntaxhighlight lang="picolisp">(in "file" (make (while (char) (link @))))</syntaxhighlight>
Encoding is always assumed to be UTF-8.
Encoding is always assumed to be UTF-8.


=={{header|Pike}}==
=={{header|Pike}}==
<lang pike>string content=Stdio.File("foo.txt")->read();</lang>
<syntaxhighlight lang="pike">string content=Stdio.File("foo.txt")->read();</syntaxhighlight>
would be the generic way of reading an entire file, but there is also a special function for it:
would be the generic way of reading an entire file, but there is also a special function for it:
<lang pike>string content=Stdio.read_file("foo.txt");</lang>
<syntaxhighlight lang="pike">string content=Stdio.read_file("foo.txt");</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
get file (in) edit ((substr(s, i, 1) do i = 1 to 32767)) (a);
get file (in) edit ((substr(s, i, 1) do i = 1 to 32767)) (a);
</syntaxhighlight>
</lang>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang powershell>Get-Content foo.txt</lang>
<syntaxhighlight lang="powershell">Get-Content foo.txt</syntaxhighlight>
This will only detect Unicode correctly with a BOM in place (even for UTF-8). With explicit selection of encoding:
This will only detect Unicode correctly with a BOM in place (even for UTF-8). With explicit selection of encoding:
<lang powershell>Get-Content foo.txt -Encoding UTF8</lang>
<syntaxhighlight lang="powershell">Get-Content foo.txt -Encoding UTF8</syntaxhighlight>
However, both return an array of strings which is fine for pipeline use but if a single string is desired the array needs to be joined:
However, both return an array of strings which is fine for pipeline use but if a single string is desired the array needs to be joined:
<lang powershell>(Get-Content foo.txt) -join "`n"</lang>
<syntaxhighlight lang="powershell">(Get-Content foo.txt) -join "`n"</syntaxhighlight>


=={{header|Prolog}}==
=={{header|Prolog}}==
Line 1,679: Line 1,748:


{{works with|SWI Prolog}}
{{works with|SWI Prolog}}
<syntaxhighlight lang="prolog">
<lang Prolog>
:- initialization(main).
:- initialization(main).


Line 1,685: Line 1,754:
current_prolog_flag(argv, [File|_]),
current_prolog_flag(argv, [File|_]),
read_file_to_string(File, String, []).
read_file_to_string(File, String, []).
</syntaxhighlight>
</lang>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
A file can be read with any of the built in commands
A file can be read with any of the built in commands
<lang PureBasic>Number.b = ReadByte(#File)
<syntaxhighlight lang="purebasic">Number.b = ReadByte(#File)
Length.i = ReadData(#File, *MemoryBuffer, LengthToRead)
Length.i = ReadData(#File, *MemoryBuffer, LengthToRead)
Number.c = ReadCharacter(#File)
Number.c = ReadCharacter(#File)
Line 1,698: Line 1,767:
Number.q = ReadQuad(#File)
Number.q = ReadQuad(#File)
Text$ = ReadString(#File [, Flags])
Text$ = ReadString(#File [, Flags])
Number.w = ReadWord(#File)</lang>
Number.w = ReadWord(#File)</syntaxhighlight>
If the file is s pure text file (no CR/LF etc.), this will work and will read each line untill EOL is found.
If the file is s pure text file (no CR/LF etc.), this will work and will read each line untill EOL is found.
<lang PureBasic>If ReadFile(0, "RC.txt")
<syntaxhighlight lang="purebasic">If ReadFile(0, "RC.txt")
Variable$=ReadString(0)
Variable$=ReadString(0)
CloseFile(0)
CloseFile(0)
EndIf</lang>
EndIf</syntaxhighlight>
Since PureBasic terminates strings with a #NULL and also split the ReadString() is encountering new line chars, any file containing these must be treated as a data stream.
Since PureBasic terminates strings with a #NULL and also split the ReadString() is encountering new line chars, any file containing these must be treated as a data stream.
<lang PureBasic>Title$="Select a file"
<syntaxhighlight lang="purebasic">Title$="Select a file"
Pattern$="Text (.txt)|*.txt|All files (*.*)|*.*"
Pattern$="Text (.txt)|*.txt|All files (*.*)|*.*"
fileName$ = OpenFileRequester(Title$,"",Pattern$,0)
fileName$ = OpenFileRequester(Title$,"",Pattern$,0)
Line 1,718: Line 1,787:
CloseFile(0)
CloseFile(0)
EndIf
EndIf
EndIf</lang>
EndIf</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==


<lang python>open(filename).read()</lang>
<syntaxhighlight lang="python">open(filename).read()</syntaxhighlight>


This returns a byte string and does not assume any particular encoding.
This returns a byte string and does not assume any particular encoding.
Line 1,728: Line 1,797:
In Python 3 strings are in unicode, you can specify encoding when reading:
In Python 3 strings are in unicode, you can specify encoding when reading:


<lang python>open(filename, encoding='utf-8').read()</lang>
<syntaxhighlight lang="python">open(filename, encoding='utf-8').read()</syntaxhighlight>


Python docs recommend dealing with files using the with statement:
Python docs recommend dealing with files using the with statement:


<lang python>with open(filename) as f:
<syntaxhighlight lang="python">with open(filename) as f:
data = f.read()</lang>
data = f.read()</syntaxhighlight>


Starting in Python 3.4, we can use <code>pathlib</code> to reduce boilerplate:
Starting in Python 3.4, we can use <code>pathlib</code> to reduce boilerplate:


<lang python>from pathlib import Path
<syntaxhighlight lang="python">from pathlib import Path


any_string = Path(filename).read_text(encoding='utf-8')
any_string = Path(filename).read_text(encoding='utf-8')
any_binary_data = Path(filename).read_bytes()</lang>
any_binary_data = Path(filename).read_bytes()</syntaxhighlight>


=={{header|Quackery}}==
=={{header|Quackery}}==
Line 1,746: Line 1,815:
<code>sharefile</code> takes a file name in a string as an argument, appends a file path if there is one on the ancillary stack <code>filepath</code>, and returns the contents of the file as a string, and <code>1</code> (i.e. true) if the file exists. If the file does not exist it returns the name of the file and <code>0</code> (i.e. false).
<code>sharefile</code> takes a file name in a string as an argument, appends a file path if there is one on the ancillary stack <code>filepath</code>, and returns the contents of the file as a string, and <code>1</code> (i.e. true) if the file exists. If the file does not exist it returns the name of the file and <code>0</code> (i.e. false).


<lang Quackery>$ "myfile.txt" sharefile</lang>
<syntaxhighlight lang="quackery">$ "myfile.txt" sharefile</syntaxhighlight>


=={{header|Q}}==
=={{header|Q}}==


<lang Q>q)file:read0`:file.txt
<syntaxhighlight lang="q">q)file:read0`:file.txt
"First line of file"
"First line of file"
"Second line of file"
"Second line of file"
""</lang>
""</syntaxhighlight>


=={{header|R}}==
=={{header|R}}==


<lang r>fname <- "notes.txt"
<syntaxhighlight lang="r">fname <- "notes.txt"
contents <- readChar(fname, file.info(fname)$size)</lang>
contents <- readChar(fname, file.info(fname)$size)</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==


<lang racket>(file->string "foo.txt")</lang>
<syntaxhighlight lang="racket">(file->string "foo.txt")</syntaxhighlight>


=={{header|Raku}}==
=={{header|Raku}}==
Line 1,768: Line 1,837:


{{works with|Rakudo|2010.07}}
{{works with|Rakudo|2010.07}}
<lang perl6>my $string = slurp 'sample.txt';</lang>
<syntaxhighlight lang="raku" line>my $string = slurp 'sample.txt';</syntaxhighlight>


The default encoding is UTF-8. The <tt>:enc</tt> adverb can be used to specify a different one:
The default encoding is UTF-8. The <tt>:enc</tt> adverb can be used to specify a different one:


<lang perl6>my $string = slurp 'sample.txt', :enc<UTF-16>;</lang>
<syntaxhighlight lang="raku" line>my $string = slurp 'sample.txt', :enc<UTF-16>;</syntaxhighlight>


<tt>IO::Path</tt> objects also provide <tt>slurp</tt> as a method:
<tt>IO::Path</tt> objects also provide <tt>slurp</tt> as a method:
<lang perl6>my $string = 'sample.txt'.IO.slurp;</lang>
<syntaxhighlight lang="raku" line>my $string = 'sample.txt'.IO.slurp;</syntaxhighlight>


=={{header|Raven}}==
=={{header|Raven}}==
<lang Raven>'myfile.txt' read as $content_as_string</lang>
<syntaxhighlight lang="raven">'myfile.txt' read as $content_as_string</syntaxhighlight>
or
or
<lang Raven>'file://r:/home/me/myfile.txt' open as $handle
<syntaxhighlight lang="raven">'file://r:/home/me/myfile.txt' open as $handle
$handle read as $content_as_string
$handle read as $content_as_string
$handle close</lang>
$handle close</syntaxhighlight>


=={{header|REALbasic}}==
=={{header|REALbasic}}==
This function accepts a file (FolderItem object) and an optional TextEncoding class. If the TextEncoding is not defined, then REALbasic defaults to UTF-8. Since it is intended for cross-platform development, REALbasic has a number of built-in tools for working with different text encodings, line terminators, etc. [http://docs.realsoftware.com/index.php/TextEncoding]
This function accepts a file (FolderItem object) and an optional TextEncoding class. If the TextEncoding is not defined, then REALbasic defaults to UTF-8. Since it is intended for cross-platform development, REALbasic has a number of built-in tools for working with different text encodings, line terminators, etc. [http://docs.realsoftware.com/index.php/TextEncoding]
<lang realbasic>
<syntaxhighlight lang="realbasic">
Function readFile(theFile As FolderItem, txtEncode As TextEncoding = Nil) As String
Function readFile(theFile As FolderItem, txtEncode As TextEncoding = Nil) As String
Dim fileContents As String
Dim fileContents As String
Line 1,798: Line 1,867:
MsgBox("File Not Found.")
MsgBox("File Not Found.")
End Function
End Function
</syntaxhighlight>
</lang>


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang rebol>read %my-file ; read as text
<syntaxhighlight lang="rebol">read %my-file ; read as text
read/binary %my-file ; preserve contents exactly</lang>
read/binary %my-file ; preserve contents exactly</syntaxhighlight>


=={{header|Retro}}==
=={{header|Retro}}==
<syntaxhighlight lang="retro">
<lang Retro>
here 'input.txt file:slurp</lang>
here 'input.txt file:slurp</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
===using LINEIN===
===using LINEIN===
<lang rexx>/*REXX program reads an entire file line-by-line and stores it as a continuous string.*/
<syntaxhighlight lang="rexx">/*REXX program reads an entire file line-by-line and stores it as a continuous string.*/
parse arg iFID . /*obtain optional argument from the CL.*/
parse arg iFID . /*obtain optional argument from the CL.*/
if iFID=='' then iFID= 'a_file' /*Not specified? Then use the default.*/
if iFID=='' then iFID= 'a_file' /*Not specified? Then use the default.*/
Line 1,816: Line 1,885:
do while lines(iFID)\==0 /*read the file's lines until finished.*/
do while lines(iFID)\==0 /*read the file's lines until finished.*/
$=$ || linein(iFID) /*append a (file's) line to the string,*/
$=$ || linein(iFID) /*append a (file's) line to the string,*/
end /*while*/ /*stick a fork in it, we're all done. */</lang>
end /*while*/ /*stick a fork in it, we're all done. */</syntaxhighlight>


===using CHARIN===
===using CHARIN===
Note that CRLF are in the resulting string.
Note that CRLF are in the resulting string.
<lang>/*REXX program reads a file and stores it as a continuous character str.*/
<syntaxhighlight lang="text">/*REXX program reads a file and stores it as a continuous character str.*/
Parse Version v
Parse Version v
iFID = 'st.in' /*name of the input file. */
iFID = 'st.in' /*name of the input file. */
Line 1,836: Line 1,905:
say 'v='v
say 'v='v
say 'length(v)='length(v)
say 'length(v)='length(v)
</lang>
</syntaxhighlight>
{{out}}
{{out}}
<pre>E:\>rexx refc
<pre>E:\>rexx refc
Line 1,846: Line 1,915:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
# Read the file
# Read the file
cStr = read("myfile.txt")
cStr = read("myfile.txt")
# print the file content
# print the file content
See cStr
See cStr
</syntaxhighlight>
</lang>


Also in one line we can read and print the file content.
Also in one line we can read and print the file content.


<lang ring>
<syntaxhighlight lang="ring">
cStr = read("myfile.txt") See cStr
cStr = read("myfile.txt") See cStr
</syntaxhighlight>
</lang>


We can avoid the string, but it's required in the task.
We can avoid the string, but it's required in the task.


<lang ring>
<syntaxhighlight lang="ring">
See read("myfile.txt")
See read("myfile.txt")
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
IO.read is for text files. It uses the default text encodings, and on Microsoft Windows, it also converts "\r\n" to "\n".
IO.read is for text files. It uses the default text encodings, and on Microsoft Windows, it also converts "\r\n" to "\n".


<lang ruby># Read entire text file.
<syntaxhighlight lang="ruby"># Read entire text file.
str = IO.read "foobar.txt"
str = IO.read "foobar.txt"


# It can also read a subprocess.
# It can also read a subprocess.
str = IO.read "| grep ftp /etc/services"</lang>
str = IO.read "| grep ftp /etc/services"</syntaxhighlight>


''Caution!'' IO.read and File.read take a portname. To open an arbitrary path (which might start with "|"), you must use File.open, then IO#read.
''Caution!'' IO.read and File.read take a portname. To open an arbitrary path (which might start with "|"), you must use File.open, then IO#read.


<lang ruby>path = "|strange-name.txt"
<syntaxhighlight lang="ruby">path = "|strange-name.txt"
str = File.open(path) {|f| f.read}</lang>
str = File.open(path) {|f| f.read}</syntaxhighlight>


To read a binary file, open it in binary mode.
To read a binary file, open it in binary mode.


<lang ruby># Read entire binary file.
<syntaxhighlight lang="ruby"># Read entire binary file.
str = File.open(path, "rb") {|f| f.read}</lang>
str = File.open(path, "rb") {|f| f.read}</syntaxhighlight>


Ruby 1.9 can read text files in different encodings.
Ruby 1.9 can read text files in different encodings.


{{works with|Ruby|1.9}}
{{works with|Ruby|1.9}}
<lang ruby># Read EUC-JP text from file.
<syntaxhighlight lang="ruby"># Read EUC-JP text from file.
str = File.open(path, "r:euc-jp") {|f| f.read}
str = File.open(path, "r:euc-jp") {|f| f.read}


# Read EUC-JP text from file; transcode text from EUC-JP to UTF-8.
# Read EUC-JP text from file; transcode text from EUC-JP to UTF-8.
str = File.open(path, "r:euc-jp:utf-8") {|f| f.read}</lang>
str = File.open(path, "r:euc-jp:utf-8") {|f| f.read}</syntaxhighlight>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang Runbasic>open DefaultDir$ + "/public/test.txt" for binary as #f
<syntaxhighlight lang="runbasic">open DefaultDir$ + "/public/test.txt" for binary as #f
fileLen = LOF(#f)
fileLen = LOF(#f)
a$ = input$(#f, fileLen)
a$ = input$(#f, fileLen)
print a$
print a$
close #f</lang>
close #f</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==


<lang rust>use std::fs::File;
<syntaxhighlight lang="rust">use std::fs::File;
use std::io::Read;
use std::io::Read;


Line 1,916: Line 1,985:
let filestr = String::from_utf8(contents).unwrap();
let filestr = String::from_utf8(contents).unwrap();
println!("{}", filestr);
println!("{}", filestr);
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
{{libheader|Scala}}
{{libheader|Scala}}
<lang scala>object TextFileSlurper extends App {
<syntaxhighlight lang="scala">object TextFileSlurper extends App {
val fileLines =
val fileLines =
try scala.io.Source.fromFile("my_file.txt", "UTF-8").mkString catch {
try scala.io.Source.fromFile("my_file.txt", "UTF-8").mkString catch {
case e: java.io.FileNotFoundException => e.getLocalizedMessage()
case e: java.io.FileNotFoundException => e.getLocalizedMessage()
}
}
}</lang>
}</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
Uses SRFI-13:
Uses SRFI-13:
<lang scheme>(with-input-from-file "foo.txt"
<syntaxhighlight lang="scheme">(with-input-from-file "foo.txt"
(lambda ()
(lambda ()
(reverse-list->string
(reverse-list->string
Line 1,936: Line 2,005:
(if (eof-object? char)
(if (eof-object? char)
result
result
(loop (read-char) (cons char result)))))))</lang>
(loop (read-char) (cons char result)))))))</syntaxhighlight>


Works with Chicken Scheme:
Works with Chicken Scheme:
<lang scheme>(with-input-from-file "foo.txt" read-string)</lang>
<syntaxhighlight lang="scheme">(with-input-from-file "foo.txt" read-string)</syntaxhighlight>


In GNU Guile, with decoding into Unicode code points:
In GNU Guile, with decoding into Unicode code points:
<lang scheme>(use-modules (ice-9 textual-ports))
<syntaxhighlight lang="scheme">(use-modules (ice-9 textual-ports))
(call-with-input-file "foo.txt" get-string-all)</lang>
(call-with-input-file "foo.txt" get-string-all)</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
Line 1,949: Line 2,018:
defines the function [http://seed7.sourceforge.net/libraries/getf.htm#getf%28in_string%29 getf],
defines the function [http://seed7.sourceforge.net/libraries/getf.htm#getf%28in_string%29 getf],
which reads a whole file into a string:
which reads a whole file into a string:
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "getf.s7i";
include "getf.s7i";


Line 1,957: Line 2,026:
begin
begin
fileContent := getf("text.txt");
fileContent := getf("text.txt");
end func;</lang>
end func;</syntaxhighlight>


=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
<lang sensetalk>Put file "~/Documents/myFile.txt" into TestFile
<syntaxhighlight lang="sensetalk">Put file "~/Documents/myFile.txt" into TestFile
put testFile</lang>
put testFile</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
Reading an entire file as a string, can be achieved with the '''FileHandle.slurp()''' method, as illustrated bellow:
Reading an entire file as a string, can be achieved with the '''FileHandle.slurp()''' method, as illustrated bellow:
<lang ruby>var file = File.new(__FILE__);
<syntaxhighlight lang="ruby">var file = File.new(__FILE__);
var content = file.open_r.slurp;
var content = file.open_r.slurp;
print content;</lang>
print content;</syntaxhighlight>


Starting with version 2.30, ''File.read()'' can do the same:
Starting with version 2.30, ''File.read()'' can do the same:
<lang ruby>var file = File(__FILE__)
<syntaxhighlight lang="ruby">var file = File(__FILE__)
var content = file.read(:utf8)
var content = file.read(:utf8)
print content</lang>
print content</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
{{works with|Pharo}}
{{works with|Pharo}}
<lang smalltalk>(StandardFileStream oldFileNamed: 'foo.txt') contents</lang>
<syntaxhighlight lang="smalltalk">(StandardFileStream oldFileNamed: 'foo.txt') contents</syntaxhighlight>
{{works with|Smalltalk/X}}
{{works with|Smalltalk/X}}
<lang smalltalk>'foo.txt' asFilename contentsAsString</lang>
<syntaxhighlight lang="smalltalk">'foo.txt' asFilename contentsAsString</syntaxhighlight>


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
In SNOBOL4, file I/O is done by associating a variable with the desired file, via the input() built-in function. After the association, each reference to the named variable provides as the variable's value the next block or line of data from the corresponding file. The exact format of the input() function parameters tends to vary based on the implementation in use. In this example, the code reads the file in blocks of 512k bytes (or less) until the entire file has been read into one long string in memory.
In SNOBOL4, file I/O is done by associating a variable with the desired file, via the input() built-in function. After the association, each reference to the named variable provides as the variable's value the next block or line of data from the corresponding file. The exact format of the input() function parameters tends to vary based on the implementation in use. In this example, the code reads the file in blocks of 512k bytes (or less) until the entire file has been read into one long string in memory.


<lang SNOBOL4> input(.inbin,21,"filename.txt [-r524288]") :f(end)
<syntaxhighlight lang="snobol4"> input(.inbin,21,"filename.txt [-r524288]") :f(end)
rdlp buf = inbin :s(rdlp)
rdlp buf = inbin :s(rdlp)
*
*
* now process the 'buf' containing the file
* now process the 'buf' containing the file
*
*
end</lang>
end</syntaxhighlight>


=={{header|Sparkling}}==
=={{header|Sparkling}}==
<lang sparkling>let contents = readfile("foo.txt");</lang>
<syntaxhighlight lang="sparkling">let contents = readfile("foo.txt");</syntaxhighlight>


=={{header|SPL}}==
=={{header|SPL}}==
<lang spl>text = #.readtext("filename.txt")</lang>
<syntaxhighlight lang="spl">text = #.readtext("filename.txt")</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<syntaxhighlight lang="sml">
<lang sml>fun readFile path =
(* string -> string *)
fun readFile path =
(fn strm =>
(fn strm =>
TextIO.inputAll strm before TextIO.closeIn strm) (TextIO.openIn path)</lang>
TextIO.inputAll strm before TextIO.closeIn strm) (TextIO.openIn path)</syntaxhighlight>
</syntaxhighlight>


=={{header|Stata}}==
=={{header|Stata}}==
It's possible to get the entire content as an array of lines with '''[http://www.stata.com/help.cgi?mf_cat cat]'''. However, here we want a single string. See '''[http://www.stata.com/help.cgi?mf_fopen fopen]''' and related functions.
It's possible to get the entire content as an array of lines with '''[http://www.stata.com/help.cgi?mf_cat cat]'''. However, here we want a single string. See '''[http://www.stata.com/help.cgi?mf_fopen fopen]''' and related functions.


<lang stata>mata
<syntaxhighlight lang="stata">mata
f = fopen("somedata.txt", "r")
f = fopen("somedata.txt", "r")
fseek(f, 0, 1)
fseek(f, 0, 1)
Line 2,011: Line 2,083:
s = fread(f, n)
s = fread(f, n)
fclose(f)
fclose(f)
end</lang>
end</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
{{works with|Swift|1}}
<lang Swift>import Foundation

<syntaxhighlight lang="swift">import Foundation


let path = "~/input.txt".stringByExpandingTildeInPath
let path = "~/input.txt".stringByExpandingTildeInPath
if let string = String(contentsOfFile: path, encoding: NSUTF8StringEncoding) {
if let string = String(contentsOfFile: path, encoding: NSUTF8StringEncoding) {
println(string) // print contents of file
println(string) // print contents of file
}</lang>
}</syntaxhighlight>

{{works with|Swift|5}}
<syntaxhighlight lang="swift">import Foundation

let path = "input.txt"
do
{
let string = try String(contentsOfFile: path, encoding: String.Encoding.utf8)
print(string) // print contents of file
}
catch
{
print("error occured: \(error)")
}
</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
This reads the data in as text, applying the default encoding translations.
This reads the data in as text, applying the default encoding translations.
<lang tcl>set f [open $filename]
<syntaxhighlight lang="tcl">set f [open $filename]
set data [read $f]
set data [read $f]
close $f</lang>
close $f</syntaxhighlight>
To read the data in as uninterpreted bytes, either use <code>fconfigure</code> to put the handle into binary mode before reading, or (from Tcl 8.5 onwards) do this:
To read the data in as uninterpreted bytes, either use <code>fconfigure</code> to put the handle into binary mode before reading, or (from Tcl 8.5 onwards) do this:
<lang tcl>set f [open $filename "rb"]
<syntaxhighlight lang="tcl">set f [open $filename "rb"]
set data [read $f]
set data [read $f]
close $f</lang>
close $f</syntaxhighlight>


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
$$ MODE TUSCRIPT
ERROR/STOP OPEN ("rosetta.txt",READ,-std-)
ERROR/STOP OPEN ("rosetta.txt",READ,-std-)
var=FILE ("rosetta.txt")
var=FILE ("rosetta.txt")
</syntaxhighlight>
</lang>


=={{header|TXR}}==
=={{header|TXR}}==


<lang txr>@(next "foo.txt")
<syntaxhighlight lang="txr">@(next "foo.txt")
@(freeform)
@(freeform)
@LINE
@LINE
</syntaxhighlight>
</lang>


The freeform directive in TXR causes the remaining lines of the text stream
The freeform directive in TXR causes the remaining lines of the text stream
Line 2,058: Line 2,147:
we tell 'printf' to add an extra newline.
we tell 'printf' to add an extra newline.


<lang sh>f=`cat foo.txt` # f will contain the entire contents of the file
<syntaxhighlight lang="sh">f=`cat foo.txt` # f will contain the entire contents of the file
printf '%s\n' "$f"</lang>
printf '%s\n' "$f"</syntaxhighlight>


<lang bash>f=$(cat foo.txt)
<syntaxhighlight lang="bash">f=$(cat foo.txt)
printf '%s\n' "$f"</lang>
printf '%s\n' "$f"</syntaxhighlight>


Some shells provide a shortcut to read a file without starting a 'cat' process.
Some shells provide a shortcut to read a file without starting a 'cat' process.
Line 2,069: Line 2,158:
{{works with|pdksh}}
{{works with|pdksh}}


<lang bash>f=$(<foo.txt)
<syntaxhighlight lang="bash">f=$(<foo.txt)
echo -E "$f"</lang>
echo -E "$f"</syntaxhighlight>


{{works with|zsh}}
{{works with|zsh}}
<lang bash>file=$(<foo.txt)
<syntaxhighlight lang="bash">file=$(<foo.txt)
print $file</lang>
print $file</syntaxhighlight>
alternatively
alternatively
<lang bash>zmodload zsh/mapfile
<syntaxhighlight lang="bash">zmodload zsh/mapfile
print $mapfile[foo.txt]</lang>
print $mapfile[foo.txt]</syntaxhighlight>


=={{header|Ursa}}==
=={{header|Ursa}}==
<lang ursa>decl string contents
<syntaxhighlight lang="ursa">decl string contents
decl file f
decl file f
f.open "filename.txt"
f.open "filename.txt"
set contents (f.readall)</lang>
set contents (f.readall)</syntaxhighlight>


=={{header|Vala}}==
=={{header|Vala}}==
<lang vala>
<syntaxhighlight lang="vala">
string file_contents;
string file_contents;
FileUtils.get_contents("foo.txt", out file_contents);
FileUtils.get_contents("foo.txt", out file_contents);
</syntaxhighlight>
</lang>


=={{header|VBScript}}==
=={{header|VBScript}}==
Read text file with default encoding into variable and display
Read text file with default encoding into variable and display
<lang vb>dim s
<syntaxhighlight lang="vb">dim s
s = createobject("scripting.filesystemobject").opentextfile("slurp.vbs",1).readall
s = createobject("scripting.filesystemobject").opentextfile("slurp.vbs",1).readall
wscript.echo s</lang>
wscript.echo s</syntaxhighlight>


Read text file with UTF-16 encoding into memory and display
Read text file with UTF-16 encoding into memory and display
<lang vb>wscript.echo createobject("scripting.filesystemobject").opentextfile("utf16encoded.txt",1,-1).readall</lang>
<syntaxhighlight lang="vb">wscript.echo createobject("scripting.filesystemobject").opentextfile("utf16encoded.txt",1,-1).readall</syntaxhighlight>


=={{header|Vedit macro language}}==
=={{header|Vedit macro language}}==
Line 2,107: Line 2,196:


Read file into edit buffer. The buffer is allocated automatically:
Read file into edit buffer. The buffer is allocated automatically:
<lang vedit>File_Open("example.txt")</lang>
<syntaxhighlight lang="vedit">File_Open("example.txt")</syntaxhighlight>


Read file into text register 10:
Read file into text register 10:
<lang vedit>Reg_Load(10, "example.txt")</lang>
<syntaxhighlight lang="vedit">Reg_Load(10, "example.txt")</syntaxhighlight>


=={{header|Visual Basic}}==
=={{header|Visual Basic}}==
{{works with|Visual Basic|5}}
{{works with|Visual Basic|5}}
{{works with|Visual Basic|6}}
{{works with|Visual Basic|6}}
<lang vb>Declare Function MultiByteToWideChar Lib "kernel32.dll" ( _
<syntaxhighlight lang="vb">Declare Function MultiByteToWideChar Lib "kernel32.dll" ( _
ByVal CodePage As Long, _
ByVal CodePage As Long, _
ByVal dwFlags As Long, _
ByVal dwFlags As Long, _
Line 2,151: Line 2,240:
Close #fn
Close #fn
Debug.Print s
Debug.Print s
End Sub</lang>
End Sub</syntaxhighlight>


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
<lang vbnet>Imports System.IO
<syntaxhighlight lang="vbnet">Imports System.IO


Public Class Form1
Public Class Form1
Line 2,169: Line 2,258:
End Sub
End Sub


End Class</lang>
End Class</syntaxhighlight>


=={{header|Wart}}==
=={{header|Wart}}==
<lang wart>with infile "x"
<syntaxhighlight lang="wart">with infile "x"
with outstring
with outstring
whilet line (read_line)
whilet line (read_line)
prn line</lang>
prn line</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
Line 2,183: Line 2,272:
For the following script, a file called "input.txt" has been created which contains the string "abcdefghijklmnopqrstuvwxyz".
For the following script, a file called "input.txt" has been created which contains the string "abcdefghijklmnopqrstuvwxyz".
<lang ecmascript>import "io" for File
<syntaxhighlight lang="wren">import "io" for File


System.print(File.read("input.txt"))</lang>
System.print(File.read("input.txt"))</syntaxhighlight>


{{out}}
{{out}}
Line 2,196: Line 2,285:
The command line is: readfile <readfile.xpl
The command line is: readfile <readfile.xpl


<lang XPL0>include c:\cxpl\codes; \intrinsic 'code' declarations
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated string convention
string 0; \use zero-terminated string convention
int I;
int I;
Line 2,208: Line 2,297:
SetHp(Str+I+1); \set heap pointer beyond Str (not really needed here)
SetHp(Str+I+1); \set heap pointer beyond Str (not really needed here)
Text(0, Str); \show file as a string
Text(0, Str); \show file as a string
]</lang>
]</syntaxhighlight>


{{Out}}
{{Out}}
Line 2,228: Line 2,317:


=={{header|Xtend}}==
=={{header|Xtend}}==
<lang java>
<syntaxhighlight lang="java">
package com.rosetta.example
package com.rosetta.example


Line 2,239: Line 2,328:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Yorick}}==
=={{header|Yorick}}==
Line 2,245: Line 2,334:
Each array element is one line.
Each array element is one line.
Each line's trailing newline is removed.
Each line's trailing newline is removed.
<lang yorick>lines = rdfile("foo.txt");</lang>
<syntaxhighlight lang="yorick">lines = rdfile("foo.txt");</syntaxhighlight>
This loads foo.txt into ''content'' as a single scalar string, without losing newlines.
This loads foo.txt into ''content'' as a single scalar string, without losing newlines.
<lang yorick>f = open("foo.txt", "rb");
<syntaxhighlight lang="yorick">f = open("foo.txt", "rb");
raw = array(char, sizeof(f));
raw = array(char, sizeof(f));
_read, f, 0, raw;
_read, f, 0, raw;
close, f;
close, f;
content = strchar(raw);</lang>
content = strchar(raw);</syntaxhighlight>

=={{header|Zig}}==

{{Works with|Zig|0.10.x}}
{{Works with|Zig|0.11.x}}
{{Works with|Zig|0.12.0-dev.1604+caae40c21}}

<syntaxhighlight lang="zig">const std = @import("std");

const File = std.fs.File;

pub fn main() (error{OutOfMemory} || File.OpenError || File.ReadError)!void {
var gpa: std.heap.GeneralPurposeAllocator(.{}) = .{};
defer _ = gpa.deinit();
const allocator = gpa.allocator();

const cwd = std.fs.cwd();

var file = try cwd.openFile("input_file.txt", .{ .mode = .read_only });
defer file.close();

const file_content = try file.readToEndAlloc(allocator, comptime std.math.maxInt(usize));
defer allocator.free(file_content);

std.debug.print("Read {d} octets. File content:\n", .{file_content.len});
std.debug.print("{s}", .{file_content});
}</syntaxhighlight>

===Using mmap===

When linking libc, will use libc mmap (or mmap64) call. Otherwise uses namespace supplied by user or std (includes support for Windows, among other things, so no need to write two separate versions like in C).

<syntaxhighlight lang="zig">const std = @import("std");

const File = std.fs.File;

pub fn main() (File.OpenError || File.SeekError || std.os.MMapError)!void {
const cwd = std.fs.cwd();

var file = try cwd.openFile("input_file.txt", .{ .mode = .read_only });
defer file.close();

const file_size = (try file.stat()).size;

const file_content = try std.os.mmap(null, file_size, std.os.PROT.READ, std.os.MAP.PRIVATE, file.handle, 0);
defer std.os.munmap(file_content);

std.debug.print("Read {d} octets. File content:\n", .{file_content.len});
std.debug.print("{s}", .{file_content});
}</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==


<lang zkl>data := File("foo.txt","r").read()</lang>
<syntaxhighlight lang="zkl">data := File("foo.txt","r").read()</syntaxhighlight>
The file parameters are the same as C's
The file parameters are the same as C's

Latest revision as of 06:23, 11 April 2024

Task
Read entire file
You are encouraged to solve this task according to the task description, using any language you may know.
Task

Load the entire contents of some text file as a single string variable.

If applicable, discuss: encoding selection, the possibility of memory-mapping.

Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case check File IO); this is for those cases where having the entire file is actually what is wanted.

11l

Translation of: Python
File(filename).read()

8th

The "slurp" word will read the entire contents of the file into memory, as-is, and give a "buffer". The ">s" converts that to a string, again "as-is"

"somefile.txt" f:slurp >s

Action!

proc MAIN()
  char array STRING
  open (1,"D:FILE.TXT",4,0)
  inputsd(1,STRING)
  close(1)
return

Ada

Ada.Direct_IO

Works with: Ada 2005

Using Ada.Directories to first ask for the file size and then Ada.Direct_IO to read the whole file in one chunk:

with Ada.Directories,
     Ada.Direct_IO,
     Ada.Text_IO;

procedure Whole_File is

   File_Name : String  := "whole_file.adb";
   File_Size : Natural := Natural (Ada.Directories.Size (File_Name));

   subtype File_String    is String (1 .. File_Size);
   package File_String_IO is new Ada.Direct_IO (File_String);

   File     : File_String_IO.File_Type;
   Contents : File_String;

begin
   File_String_IO.Open  (File, Mode => File_String_IO.In_File,
                               Name => File_Name);
   File_String_IO.Read  (File, Item => Contents);
   File_String_IO.Close (File);

   Ada.Text_IO.Put (Contents);
end Whole_File;

This kind of solution is limited a bit by the fact that the GNAT implementation of Ada.Direct_IO first allocates a copy of the read object on the stack inside Ada.Direct_IO.Read. On Linux you can use the command "limit stacksize 1024M" to increase the available stack for your processes to 1Gb, which gives your program more freedom to use the stack for allocating objects.

POSIX.Memory_Mapping

Works with: POSIX
Works with: Ada 95

Mapping the whole file into the address space of your process and then overlaying the file with a String object.

with Ada.Text_IO,
     POSIX.IO,
     POSIX.Memory_Mapping,
     System.Storage_Elements;

procedure Read_Entire_File is

   use POSIX, POSIX.IO, POSIX.Memory_Mapping;
   use System.Storage_Elements;

   Text_File    : File_Descriptor;
   Text_Size    : System.Storage_Elements.Storage_Offset;
   Text_Address : System.Address;

begin
   Text_File := Open (Name => "read_entire_file.adb",
                      Mode => Read_Only);
   Text_Size := Storage_Offset (File_Size (Text_File));
   Text_Address := Map_Memory (Length     => Text_Size,
                               Protection => Allow_Read,
                               Mapping    => Map_Shared,
                               File       => Text_File,
                               Offset     => 0);

   declare
      Text : String (1 .. Natural (Text_Size));
      for Text'Address use Text_Address;
   begin
      Ada.Text_IO.Put (Text);
   end;

   Unmap_Memory (First  => Text_Address,
                 Length => Text_Size);
   Close (File => Text_File);
end Read_Entire_File;

Character encodings and their handling are not really specified in Ada. What Ada does specify is three different character types (and corresponding string types):

  • Character - containing the set of ISO-8859-1 characters.
  • Wide_Character - containing the set of ISO-10646 BMP characters.
  • Wide_Wide_Character - containing the full set of ISO-10646 characters.

The GNU Ada compiler (GNAT) seems to read in text files as bytes, completely ignoring any operating system information on character encoding. You can use -gnatW8 in Ada 2005 mode to use UTF-8 characters in identifier names.

ALGOL 68

In official ALGOL 68 a file is composed of pages, lines and characters, however for ALGOL 68 Genie and ELLA ALGOL 68RS this concept is not supported as they adopt the Unix concept of files being "flat", and hence contain only characters.

The book can contain new pages and new lines, are not of any particular character set, hence are system independent. The character set is set by a call to make conv, eg make conv(tape, ebcdic conv); - c.f. Character_codes for more details.

In official/standard ALGOL 68 only:

MODE BOOK = FLEX[0]FLEX[0]FLEX[0]CHAR; ¢ pages of lines of characters ¢
BOOK book;

FILE book file;
INT errno = open(book file, "book.txt", stand in channel);

get(book file, book)

Once a "book" has been read into a book array it can still be associated with a virtual file and again be accessed with standard file routines (such as readf, printf, putf, getf, new line etc). This means data can be directly manipulated from a array cached in "core" using transput (stdio) routines.

In official/standard ALGOL 68 only:

FILE cached book file;
associate(cached book file, book)

Amazing Hopper

Hopper only stores 1 BM of characters for each string variable. If the file to be read "all at once" exceeds that size, the file can be read, and every 1MB saved in a row of a dynamic array of strings, using the PUSH instruction for each portion read. In this way, it is possible to work with portions of a file.

For now, only a simple version is shown.

#include <hopper.h>

main:
   s=""
   load str ("archivo.txt") (s)
   println ( "File loaded:\n",s )
exit(0)
Output:
File loaded:
RX/RY,A,B,C,D,E,F,G,H,I,J
fila 1,1,2,3,4,5,6,7.998,8,9.034,10
fila 2,10,20,30,40,50,60,70,80,90,100
fila 3,100,200,300.5,400,500,600,700,800,900,1000
fila 4,5,10,15,20,25,30,35,40,45,50
fila 5,a,b,c,d,e,f,g,h,i,j
fila 6,1,2,3,4,5,6,7,8,9,10

AppleScript

set pathToTextFile to ((path to desktop folder as string) & "testfile.txt")

-- short way: open, read and close in one step
set fileContent to read file pathToTextFile

-- long way: open a file reference, read content and close access
set fileRef to open for access pathToTextFile
set fileContent to read fileRef
close access fileRef

Arturo

contents: read "input.txt"

ATS

There are various functions in the ATS prelude, including this one that is based on fread(3) and returns Strptr1:

val s = fileref_get_file_string (stdin_ref)

Because Strptr1 is a NUL-terminated string, fileref_get_file_string cannot be used for data that contains bytes equal to zero.

AutoHotkey

fileread, varname, C:\filename.txt ; adding "MsgBox %varname%" (no quotes) to the next line will display the file contents.

This script works fine as-is provided C:\filename.txt exists.

AutoIt

$fileOpen = FileOpen("file.txt")
$fileRead = FileRead($fileOpen)
FileClose($fileOpen)

AWK

#!/usr/bin/awk -f
BEGIN { 
   ## empty record separate, 
   RS="";
   ## read line (i.e. whole file) into $0	
   getline; 	
   ## print line number and content of line 
   print "=== line "NR,":",$0; 
}
{
   ## no further line is read printed 
   print "=== line "NR,":",$0; 
}
Works with: gawk
#!/usr/bin/awk -f

@include "readfile"

BEGIN {

  str = readfile("file.txt")
  print str

}

BaCon

For string data:

content$ = LOAD$(filename$)

For memory mapped binary data:

binary = BLOAD("somefile.bin")
PRINT "First two bytes are: ", PEEK(binary), " ", PEEK(binary+1)
FREE binary

BASIC

Whether or not various encodings are supported is implementation-specific.

Works with: QBasic
DIM f AS STRING
OPEN "file.txt" FOR BINARY AS 1
f = SPACE$(LOF(1))
GET #1, 1, f
CLOSE 1

Applesoft BASIC

 100 D$ =  CHR$ (4)
 110 F$ = "INPUT.TXT"
 120  PRINT D$"VERIFY"F$
 130  PRINT D$"OPEN"F$
 140  PRINT D$"READ"F$
 150  ONERR  GOTO 210
 160  GET C$
 170  POKE 216,0
 180 S$ = S$ + C$
 190  PRINT 
 200  GOTO 140
 210  POKE 216,0
 220 EOF =  PEEK (222) = 5
 230  IF  NOT EOF THEN  RESUME 
 240  PRINT D$"CLOSE"F$

Commodore BASIC

10 rem load the entire contents of some text file as a single string variable.
20 rem should avoid reading an entire file at once if the file is large
30 rem ================================
40 print chr$(14) : rem switch to upper+lowercase character set
50 open 4,8,4,"data.txt,seq,read"
60 n=0
70 for i=0 to 1
80 get#4,x$
90 i=st and 64 : rem check for 'end-of-file'
100 if i=0 then a$=a$+x$ : n=n+1
110 if n=255 then i=1 : rem max string length is 255 only
120 next
130 close 4
140 end

BASIC256

f = freefile
open f, "input.txt"
while not eof(f)
    linea$ = readline(f)
    print linea$
end while
close f

OxygenBasic

Two Formats:

string s

'AS FUNCTION
s=GetFile "t.txt"

'AS PROCEDURE
Getfile "t.txt",s

True BASIC

OPEN #2: NAME "input.txt", ORG TEXT, ACCESS INPUT, CREATE OLD
DO
   LINE INPUT #2: linea$
   PRINT linea$
LOOP UNTIL END #2
CLOSE #2
END

Yabasic

open "input.txt" for reading as #1
while not eof(1)
    line input #1 linea$
    print linea$
wend
close #1

Or also

a = open("input.txt")
while not eof(a)
    line input #a linea$
    print linea$
wend

BBC BASIC

In BBC BASIC for Windows and Brandy BASIC the maximum string length is 65535 characters.

      file% = OPENIN("input.txt")
      strvar$ = ""
      WHILE NOT EOF#file%
        strvar$ += CHR$(BGET#file%)
      ENDWHILE
      CLOSE #file%

API version:

      file% = OPENIN("input.txt")
      strvar$ = STRING$(EXT#file%, " ")
      SYS "ReadFile", @hfile%(file%), !^strvar$, EXT#file%, ^temp%, 0
      CLOSE #file%

Blue

Linux/x86-64. Reads the entire file via the mmap system call.

global _start

: syscall ( num:eax -- result:eax ) syscall ;

: exit ( status:edi -- noret ) 60 syscall ;
: bye ( -- noret ) 0 exit ;
: die ( err:eax -- noret ) neg exit ;

: unwrap ( result:eax -- value:eax ) dup 0 cmp ' die xl ;
: ordie ( result -- ) unwrap drop ;

: open ( pathname:edi flags:esi -- fd:eax ) 2 syscall unwrap ;
: close ( fd:edi -- ) 3 syscall ordie ;

48 resb stat_buf
8 resb file-size
88 resb padding

: fstat ( fd:edi buf:esi -- ) 5 syscall ordie ;

1 const prot_read
2 const map_private

: mmap ( fd:r8d len:esi addr:edi off:r9d prot:edx flags:r10d -- buf:eax ) 9 syscall unwrap ;
: munmap ( addr:edi len:esi -- ) 11 syscall ordie ;

1 resd fd
0 const read-only

: open-file ( pathname:edi -- ) read-only open fd ! ;
: read-file-size ( -- ) fd @ stat_buf fstat ;
: map-file ( fd len -- buf ) 0 0 prot_read map_private mmap ;
: map-file ( -- buf ) fd @ file-size @ map-file ;
: unmap-file ( buf -- ) file-size @ munmap ;
: close-file ( -- ) fd @ close ;

: open-this-file ( -- ) s" read_entire_file.blue" drop open-file ;

: _start ( -- noret ) 
	open-this-file
	read-file-size
	map-file
	\ do something ...
	unmap-file
	close-file 
	bye 
;

BQN

File related operations are provided under the system namespace •file. More can be seen under here.

•file.Chars "file"
•file.Bytes "file"

# Shorthands:
•FChars "file"
•FBytes "file"

•file.MapBytes returns an equivalent result to •file.Bytes, using a memory-mapped file to load the contents on demand. It can be sliced with and to get part of the file without loading the rest. As BQN arrays are immutable, there's no way to write to the file using this result.

Bracmat

get'(filename,STR):?myString

Brainf***

While the language certainly doesn't support strings in the traditional sense, relaxing the definition to mean any contiguous sequence of null-terminated bytes permits a reasonable facsimile. This cat program eschews the simpler byte-by-byte approach (,[.,]) to demonstrate the technique.

>     Keep cell 0 at 0 as a sentinel value
,[>,] Read into successive cells until EOF
<[<]  Go all the way back to the beginning
>[.>] Print successive cells while nonzero
Output:
$ curl -Ls rosettacode.org | bf ">,[>,]<[<]>[.>]"
<!DOCTYPE html>
...
</html>
Tape: [0, 60, 33, 68, 79, 67, 84, 89, 80, 69, 32, 104, 116, 109, 108, 62, 10 ... 60, 47, 104, 116, 109, 108, 62, 10, 0]

Brat

include :file

file.read file_name

C

It is not possible to specify encodings: the file is read as binary data (on some system, the b flag is ignored and there's no difference between "r" and "rb"; on others, it changes the way the "new lines" are treated, but this should not affect fread)

#include <stdio.h>
#include <stdlib.h>

int main()
{
  char *buffer;
  FILE *fh = fopen("readentirefile.c", "rb");
  if ( fh != NULL )
  {
    fseek(fh, 0L, SEEK_END);
    long s = ftell(fh);
    rewind(fh);
    buffer = malloc(s);
    if ( buffer != NULL )
    {
      fread(buffer, s, 1, fh);
      // we can now close the file
      fclose(fh); fh = NULL;
      
      // do something, e.g.
      fwrite(buffer, s, 1, stdout);

      free(buffer);
    }
    if (fh != NULL) fclose(fh);
  }
  return EXIT_SUCCESS;
}

Memory map

Works with: POSIX

We can memory-map the file.

#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

int main()
{
  char *buffer;
  struct stat s;

  int fd = open("readentirefile_mm.c", O_RDONLY);
  if (fd < 0 ) return EXIT_FAILURE;
  fstat(fd, &s);
  /* PROT_READ disallows writing to buffer: will segv */
  buffer = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);

  if ( buffer != (void*)-1 )
  {
    /* do something */
    fwrite(buffer, s.st_size, 1, stdout);
    munmap(buffer, s.st_size);
  }

  close(fd);
  return EXIT_SUCCESS;
}
Works with: Windows

Memory map on Windows. See MSDN, starting with File Mapping. In practice, it would be necessary to check for errors, and to take care of large files. Also, this example is using a view on the whole file, but it's possible to create a smaller view.

#include <windows.h>
#include <stdio.h>

int main() {
    HANDLE hFile, hMap;
    DWORD filesize;
    char *p;
    
    hFile = CreateFile("mmap_win.c", GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    filesize = GetFileSize(hFile, NULL);
    hMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
    p = MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0);

    fwrite(p, filesize, 1, stdout);
    
    CloseHandle(hMap);
    CloseHandle(hFile);
    return 0;
}

C#

Works with: C sharp version 3.0
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        var fileContents = File.ReadAllText("c:\\autoexec.bat");  
        // Can optionally take a second parameter to specify the encoding, e.g. File.ReadAllText("c:\\autoexec.bat", Encoding.UTF8)
    }
}

C++

#include <iostream>
#include <fstream>
#include <string>
#include <iterator>

int main( ) 
{
    if (std::ifstream infile("sample.txt"))
    {
        // construct string from iterator range
        std::string fileData(std::istreambuf_iterator<char>(infile), std::istreambuf_iterator<char>());

        cout << "File has " << fileData.size() << "chars\n";

        // don't need to manually close the ifstream; it will release the file when it goes out of scope
        return 0;
   }
   else 
   {
      std::cout << "file not found!\n";
      return 1;
   }
}

Clojure

The core function slurp does the trick; you can specify an encoding as an optional second argument:

(slurp "myfile.txt")
(slurp "my-utf8-file.txt" "UTF-8")

CMake

Sets a variable named string.

file(READ /etc/passwd string)

This works with text files, but fails with binary files that contain NUL characters. CMake truncates the string at the first NUL character, and there is no way to detect this truncation.

The only way to read binary files is to use the HEX keyword to convert the entire file to a hexadecimal string.

file(READ /etc/pwd.db string HEX)

Common Lisp

The following will read and store the file as a sequence of bytes.

(defun file-string (path)
  (with-open-file (stream path)
    (let ((data (make-string (file-length stream))))
      (read-sequence data stream)
      data)))

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.

Crystal

The simplest way to read an entire file to a string is by using File.read:

content = File.read("input.txt")
puts content
Output:
Lorem ipsum dolor sit amet, consectetur adipiscing elit nullam.

The encoding is UTF-8 by default, but it can be explicitly specified:

content = File.read("input.txt", "UTF-16")

or

content = File.read("input.txt", encoding: "UTF-16")

File.open allows for more options and closes the file implicitly. Combine it with File#gets_to_end to read the entire file:

content = File.open("input.txt") do |file|
  file.gets_to_end
end

Or no implicit closing at all with File.new:

file = File.new("input.txt")
content = file.gets_to_end
file.close

D

import std.file: read, readText;

void main() {
    // To read a whole file into a dynamic array of unsigned bytes:
    auto data = cast(ubyte[])read("unixdict.txt");

    // To read a whole file into a validated UTF-8 string:
    string txt = readText("unixdict.txt");
}

Delphi

Using TStringList

program ReadAll;

{$APPTYPE CONSOLE}

uses Classes;

var
  i: Integer;
  lList: TStringList;
begin
  lList := TStringList.Create;
  try
    lList.LoadFromFile('c:\input.txt');
    // Write everything at once
    Writeln(lList.Text);
    // Write one line at a time
    for i := 0 to lList.Count - 1 do
      Writeln(lList[i]);
  finally
    lList.Free;
  end;
end.


Works with: Delphi 2010 and above

program ReadAll;

{$APPTYPE CONSOLE}

uses
  SysUtils, IOUtils;

begin
// with default encoding:
  Writeln(TFile.ReadAllText('C:\autoexec.bat'));
// with encoding specified:
  Writeln(TFile.ReadAllText('C:\autoexec.bat', TEncoding.ASCII));
  Readln;
end.

Déjà Vu

To get a string from a file, you need to explicitly decode the binary blob that is read. Currently only UTF-8 is supported by vu.

local :filecontents !decode!utf-8 !read "file.txt"

E

<file:foo.txt>.getText()

The file is assumed to be in the default encoding.

Ecstasy

A  File  object in Ecstasy has a  contents  property, which yields a  Byte[]  value:

static Byte[] contentsOf(File file) {
    return file.contents;
}

There are also a few ways to obtain the contents of a file at compile-time as a literal instead of reading it at runtime. These examples show how a byte array literal and a string literal can be obtained from two different files, one using a relative path and one using an absolute path:

Byte[] bytes = #./checkmark.ico;
String html  = $/docs/website/index.htm;

The compiler can even include those files as "file objects"; the files are compiled into the compiled form of the Ecstasy module by the compiler, so their contents reflect the state of those files as they were at compile time:

File iconFile = ./checkmark.ico;
File htmlFile = /docs/website/index.htm;

Byte[] bytes = iconFile.contents;
String html  = htmlFile.contents.unpackUtf8();

Elixir

Two solutions in the FileReader namespace. File returns a tuple: {:ok, file} is successful or {:error, reason} if unsuccessful. Errors can be caught and turned into error strings via Erlang's :file.format_error function.

defmodule FileReader do
  # Read in the file
  def read(path) do
    case File.read(path) do
      {:ok, body} ->
        IO.inspect body
      {:error,reason} ->
        :file.format_error(reason)
      end
    end

  # Open the file path, then read in the file
  def bit_read(path) do
    case File.open(path) do
      {:ok, file} ->
        # :all can be replaced with :line, or with a positive integer to specify the number of characters to read.
	IO.read(file,:all)
	  |> IO.inspect
      {:error,reason} ->
	:file.format_error(reason)
    end
  end
end

Emacs Lisp

insert-file-contents does all Emacs' usual character coding, magic file names, decompression, format decoding, etc. (insert-file-contents-literally can avoid that if unwanted.)

(setq my-variable (with-temp-buffer
                    (insert-file-contents "foo.txt")
                    (buffer-string)))

(If an existing buffer is visiting the file, perhaps yet unsaved, it may be helpful to take its contents instead of re-reading the file. find-buffer-visiting can locate such a buffer.)

Erlang

{ok, B} = file:read_file("myfile.txt").

This reads the entire file into a binary object.

Euphoria

Euphoria cannot natively handle multibyte character encodings. The openEuphoria team is/was working on supporting it. It may have been implemented by now.

function load_file(sequence filename)
  integer fn,c
  sequence data
    fn = open(filename,"r") -- "r" for text files, "rb" for binary files
    if (fn = -1) then return {} end if -- failed to open the file

    data = {} -- init to empty sequence
    c = getc(fn) -- prime the char buffer
    while (c != -1) do -- while not EOF
      data &= c -- append each character
      c = getc(fn) -- next char
    end while

    close(fn)
    return data
end function

F#

// read entire file into variable using default system encoding or with specified encoding
open System.IO
let data = File.ReadAllText(filename)
let utf8 = File.ReadAllText(filename, System.Text.Encoding.UTF8)

Factor

USING: io.encodings.ascii io.encodings.binary io.files ;

! to read entire file as binary
"foo.txt" binary file-contents

! to read entire file as lines of text
"foo.txt" ascii file-lines

Fantom

Provide the filename to read from as a command-line parameter.

class ReadString
{
  public static Void main (Str[] args)
  {
    Str contents := File(args[0].toUri).readAllStr
    echo ("contents: $contents")
  }
}

Forth

Works with: GNU Forth
s" foo.txt" slurp-file   ( str len )

Fortran

Reading the entire source file in memory, then printing it. It relies on the SIZE attribute of the INQUIRE statement returning the size of the file in bytes, whereupon the ALLOCATE statement prepares a variable of the right size to receive the whole content. This SIZE facility was introduced with F2003, and prior to F90 there was no ALLOCATE facility: the size of variables was fixed at compile time.

program read_file
    implicit none
    integer :: n
    character(:), allocatable :: s
    
    open(unit=10, file="read_file.f90", action="read", &
         form="unformatted", access="stream")
    inquire(unit=10, size=n)
    allocate(character(n) :: s)
    read(10) s
    close(10)
    
    print "(A)", s
end program

Intel Fortran on Windows

Here is a solution using the Windows API to create a memory map of a file. It is used to print the source code of the program on the console.

program file_win
    use kernel32
    use iso_c_binding
    implicit none
    
    integer(HANDLE) :: hFile, hMap, hOutput
    integer(DWORD) :: fileSize
    integer(LPVOID) :: ptr
    integer(LPDWORD) :: charsWritten
    integer(BOOL) :: s
    
    hFile = CreateFile("file_win.f90" // c_null_char, GENERIC_READ, &
                       0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)
    filesize = GetFileSize(hFile, NULL)
    hMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL)
    ptr = MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0)
    
    hOutput = GetStdHandle(STD_OUTPUT_HANDLE)
    s = WriteConsole(hOutput, ptr, fileSize, transfer(c_loc(charsWritten), 0_c_intptr_t), NULL)
    s = CloseHandle(hMap)
    s = CloseHandle(hFile)
end program

FreeBASIC

' FB 1.05.0 Win64

Open "input.txt" For Input Encoding "ascii" As #1
Dim fileLen As LongInt = Lof(1) '' get file length in bytes
Dim buffer As String = Space(fileLen) '' allocate a string of size 'fileLen' bytes
Get #1, 1, buffer '' read all data from start of file into the buffer
Print buffer  '' print to console
buffer = ""  '' release memory used by setting buffer to empty
Close #1
Sleep

Frink

The read[URL] function reads the entire contents of a URL. The encoding can be specified if necessary.

a = read["file:yourfile.txt"]
b = read["file:yourfile.txt", "UTF-8"]

FutureBasic

Note: This code goes beyond simply specifying the file to open. It includes a dialog window (openpanel) that allows the user to select a text file to read. Depending on system memory, as many as 4.2 billion characters can be read. The file contents are placed in a convenient scrolling textview. (Did I mention that FutureBasic -- or FB as developers prefer to call it -- is handy for Macintosh development!) Of course, the programmer is free to code his own window and menu options.

_window = 1
begin enum 1
  _scrollView
  _textView
end enum

void local fn BuildWindow
  CGRect r = {0,0,550,400}
  window _window, @"Read Entire File", r
  scrollview _scrollView, r
  ViewSetAutoresizingMask( _scrollView, NSViewWidthSizable + NSViewHeightSizable )
  textview _textView,, _scrollView
end fn

local fn ReadTextFile
  CFStringRef string
  CFURLRef url = openpanel 1, @"Select text file..."
  if ( url )
    string = fn StringWithContentsOfURL( url, NSUTF8StringEncoding, NULL )
    TextSetString( _textView, string )
  else
    // user cancelled
  end if
end fn

fn BuildWindow
fn ReadTextFile

HandleEvents

Gambas

Public Sub Form_Open()
Dim sFile As String

sFile = File.Load(User.home &/ "file.txt")

End

GAP

InputTextFile("input.txt");
s := ReadAll(f);;  # two semicolons to hide the result, which may be long
CloseStream(f);

Genie

[indent=4]
/*
   Read entire file, in Genie

   valac readEntireFile.gs
   ./readEntireFile [filename]
*/

init

    fileName:string
    fileContents:string
    fileName = (args[1] is null) ? "readEntireFile.gs" : args[1]

    try
        FileUtils.get_contents(fileName, out fileContents)
    except exc:Error
        print "Error: %s", exc.message
        return

    stdout.printf("%d bytes read from %s\n", fileContents.length, fileName)
Output:
prompt$ valac readEntireFile.gs
prompt$ ./readEntireFile
443 bytes read from readEntireFile.gs
prompt$ ./readEntireFile nofile
Error: Failed to open file ?nofile?: No such file or directory
prompt$ ./readEntireFile leapYear.gs
291 bytes read from leapYear.gs

Go

Go has good support for working with strings as UTF-8, but there is no requirement that strings be UTF-8 and in fact they can hold arbitrary data. ioutil.ReadFile returns the contents of the file unaltered as a byte array. The conversion in the next line from byte array to string also makes no changes to the data. In the example below sv will have an exact copy of the data in the file, without regard to encoding.

import "io/ioutil"

data, err := ioutil.ReadFile(filename)
sv := string(data)

Go also supports memory mapped files on OSes with a mmap syscall (e.g. Unix-like). The following prints the contents of "file". (The included "build constraint" prevents this from being compiled on architectures known to lack syscall.Mmap, another source file with the opposite build constraint could use ioutil.ReadFile as above).

// +build !windows,!plan9,!nacl // These lack syscall.Mmap

package main

import (
    "fmt"
    "log"
    "os"
    "syscall"
)

func main() {
    f, err := os.Open("file")
    if err != nil {
        log.Fatal(err)
    }
    fi, err := f.Stat()
    if err != nil {
        log.Fatal(err)
    }
    data, err := syscall.Mmap(int(f.Fd()), 0, int(fi.Size()),
        syscall.PROT_READ, syscall.MAP_PRIVATE)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(data))
}

Groovy

def fileContent = new File("c:\\file.txt").text

GUISS

Start,Programs,Accessories,Notepad,Menu:File,Open,Doubleclick:Icon:Notes.TXT,Button:OK

Haskell

In the IO monad:

do text <- readFile filepath
   -- do stuff with text

Note that readFile is lazy. If you want to ensure the entire file is read in at once, before any other IO actions are run, try:

eagerReadFile :: FilePath -> IO String
eagerReadFile filepath = do
    text <- readFile filepath
    last text `seq` return text

Icon and Unicon

The first code snippet below reads from stdin directly into the string fs, preserving line separators (if any) and reading in large chunks.

every (fs := "") ||:= |reads(1000000)

The second code snippet below performs the same operation using an intermediate list fL and applying a function (e.g. FUNC) to each line. Use this form when you need to perform additional string functions such as 'trim' or 'map' on each line. This avoids unnecessary garbage collections which will occur with larger files. The list can be discarded when done. Line separators are mapped into newlines.

every put(fL := [],|FUNC(read()))
every (fs := "") ||:= !fL || "\n"
fL := &null

Inform 7

File access is sandboxed by the interpreter, so this solution essentially requires that the file have been previously written by an Inform program running from the same location under the same interpreter.

Home is a room.

The File of Testing is called "test".

When play begins:
	say "[text of the File of Testing]";
	end the story.

J

   require 'files'         NB. not needed for J7 & later
   var=: fread 'foo.txt'

To memory map the file:

   require 'jmf'
   JCHAR map_jmf_ 'var';'foo.txt'

Caution: updating the value of the memory mapped variable will update the file, and this characteristic remains when the variable's value is passed, unmodified, to a verb which modifies its own local variables.

Jakt

fn main() {
    let filename = "Read_entire_file.jakt"
    mut file = File::open_for_reading(filename)
    mut builder = StringBuilder::create()
    for byte in file.read_all() {
        builder.append(byte)
    }
    let contents = builder.to_string()
    println("{}", contents)
}

Java

There is no single method to do this in Java 6 and below (probably because reading an entire file at once could fill up your memory quickly), so to do this you could simply append the contents as you read them into a buffer.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {
    public static void main(String[] args) throws IOException{
        String fileContents = readEntireFile("./foo.txt");
    }

    private static String readEntireFile(String filename) throws IOException {
        FileReader in = new FileReader(filename);
        StringBuilder contents = new StringBuilder();
        char[] buffer = new char[4096];
        int read = 0;
        do {
            contents.append(buffer, 0, read);
            read = in.read(buffer);
        } while (read >= 0);
        in.close();
        return contents.toString();
    }
}

One can memory-map the file in Java, but there's little to gain if one is to create a String out of the file:

import java.nio.channels.FileChannel.MapMode;
import java.nio.MappedByteBuffer;
import java.io.RandomAccessFile;
import java.io.IOException;
import java.io.File;

public class MMapReadFile {
	public static void main(String[] args) throws IOException {
		MappedByteBuffer buff = getBufferFor(new File(args[0]));
                String results = new String(buff.asCharBuffer());
	}
	
	public static MappedByteBuffer getBufferFor(File f) throws IOException {  
		RandomAccessFile file = new RandomAccessFile(f, "r");
	
		MappedByteBuffer buffer = file.getChannel().map(MapMode.READ_ONLY, 0, f.length());
		file.close();
		return buffer;
	}
}

or one can take a shortcut:

String content = new Scanner(new File("foo"), "UTF-8").useDelimiter("\\A").next();

this works because Scanner will search the file for a delimiter and return everything before that. \A is the beginning of the file, which it will never find until the end of the file is reached.

Works with: Java version 7+

Java 7 added java.nio.file.Files which has two methods for accomplishing this task: Files.readAllLines and Files.readAllBytes:

import java.util.List;
import java.nio.charset.Charset;
import java.nio.file.*;

public class ReadAll {
	public static List<String> readAllLines(String filesname){
		Path file = Paths.get(filename);
		return Files.readAllLines(file, Charset.defaultCharset());
	}
	
	public static byte[] readAllBytes(String filename){
		Path file = Paths.get(filename);
		return Files.readAllBytes(file);
	}
}
Works with: Java version 11+

Java 11 added the method readString:

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

public class ReadAll {
    public static void main(String[] args) {
        System.out.print(Files.readString(Path.of(args[0], StandardCharsets.UTF_8)));
    }
}

JavaScript

This works in IExplorer or a standalone js file. Note the similarity to the VBScript code.

var fso=new ActiveXObject("Scripting.FileSystemObject");
var f=fso.OpenTextFile("c:\\myfile.txt",1);
var s=f.ReadAll();
f.Close();
try{alert(s)}catch(e){WScript.Echo(s)}

The following works in all browsers, including IE10.

var file = document.getElementById("fileInput").files.item(0); //a file input element
if (file) {
	var reader = new FileReader();
	reader.readAsText(file, "UTF-8");
	reader.onload = loadedFile;
	reader.onerror = errorHandler;
}
function loadedFile(event) {
	var fileString = event.target.result;
	alert(fileString);
}
function errorHandler(event) {
	alert(event);
}

jq

The . filter will read in a file of raw text, e.g. if the file is named input.txt and we wanted to emit it as a single JSON string:

jq -R -s . input.txt

In practice, this is probably not very useful. It would be more typical to collect the raw lines into an array of JSON strings.

If it is known that the lines are delimited by a single "newline" character, then one could simply pipe from one jq command to another:

jq -R . input.txt | jq -s .

Equivalently:

jq -R -s 'split("\n")' input.txt

Other cases can be similarly handled.

Jsish

var contents = File.read("filename")

From the shell:

Output:
prompt$ jsish
Jsish interactive: see 'help [cmd]'
# var contents = File.read("README")
variable
# contents
"Jsi is a small javascript interpreter for embedded-C development.

Internally Jsi emulates Tcl.  The parser and execution engine originate from quad_wheel,

It is being developed under an MIT license.

"

Julia

The built-in function read, when used with a second argument of String, reads the whole file named by its first argument into a string (assuming UTF8 encoding).

read("/devel/myfile.txt", String) # read file into a string

Alternatively, for files that are too large to read into memory without swapping, there are a variety of ways to memory-map the file, for example as an array of bytes:

A = Mmap.mmap(open("/devel/myfile.txt"), Array{UInt8,1})

K

Works with: ngn/k
`c$1:"example.txt"

The following might be more idiomatic, but returns a list of strings, corresponding to the lines of the file, rather than a single string.

0:"example.txt"

KAP

The built-in function io:readFile will read the entire content of the file as a string:

content ← io:readFile "file.txt"

The function io:read can be used to return all the lines in the file as an array:

content ← io:read "file.txt"

Kotlin

import java.io.File

fun main(args: Array<String>) {
    println(File("unixdict.txt").readText(charset = Charsets.UTF_8))
}

LabVIEW

This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.

Lang5

'foo.txt slurp

Lasso

By default, string objects, which are always Unicode, are created with the assumption that the file contains UTF-8 encoded data. This assumption can be changed by settings the file objects’s character encoding value. When reading the data as a bytes object, the unaltered file data is returned.

local(f) = file('foo.txt')
#f->readString

LFE

(set `#(ok ,data) (file:read_file "myfile.txt"))

Liberty BASIC

filedialog "Open a Text File","*.txt",file$
if file$<>"" then
    open file$ for input as #1
    entire$ = input$(#1, lof(#1))
    close #1
    print entire$
end if

Lingo

----------------------------------------
-- Reads whole file, returns string
-- @param {string} tFile
-- @return {string|false}
----------------------------------------
on readFile (tFile)
  fp = xtra("fileIO").new()
  fp.openFile(tFile, 1)
  if fp.status() then return false
  res = fp.readFile()
  fp.closeFile()
  return res
end

LiveCode

Livecode offers 2 ways:

Using URL

put URL "file:///usr/share/dict/words" into tVar
put the number of lines of tVar

Using file open + read + close

local tFile,tLinecount
put "/usr/share/dict/words" into tFile
open file tFile for text read
read from file tFile until EOF
put the number of lines of it  -- file contents held in "it" variable
close file tFile

Lua

--If the file opens with no problems, io.open will return a
--handle to the file with methods attached.
--If the file does not exist, io.open will return nil and
--an error message.
--assert will return the handle to the file if present, or
--it will throw an error with the message returned second
--by io.open.
local file = assert(io.open(filename))
--Without wrapping io.open in an assert, local file would be nil,
--which would cause an 'attempt to index a nil value' error when
--calling file:read.

--file:read takes the number of bytes to read, or a string for
--special cases, such as "*a" to read the entire file.
local contents = file:read'*a'

--If the file handle was local to the expression
--(ie. "assert(io.open(filename)):read'a'"),
--the file would remain open until its handle was
--garbage collected.
file:close()

M2000 Interpreter

Module checkit {
      \\ prepare a file
      \\ Save.Doc and Append.Doc  to file, Load.Doc and Merge.Doc from file
      document a$
      a$={First Line
            Second line
            Third Line
            Ελληνικά Greek Letters
            }
      Save.Doc a$, "checkthis.txt", 2  ' 2 for UTF-8
      
      Buffer1=Buffer("checkthis.txt")
      Print Len(Buffer1)=Filelen("checkthis.txt")
      b$=String$(Eval$(Buffer1, 0) as UTF8Dec)
      Report b$
      openfile$=FILE$("text file","txt")
      Merge.doc a$, openfile$
      Edit.Doc a$
}
checkit

M4

An approximation to file reading can be had by include() which reads a file as M4 input. If it's inside a define() then the input is captured as a definition. But this is extremely limited since any macro names, parens, commas, quote characters etc in the file will expand and upset the capture.

define(`foo',include(`file.txt'))
defn(`foo')
defn(`foo')

Make

Works with: GNU make
contents := $(shell cat foo.txt)

This is from the GNU Make manual. As noted there, newlines are converted to spaces in the $(contents) variable. This might be acceptable for files which are a list of words anyway.

Maple

First solution:

s1 := readbytes( "file1.txt", infinity, TEXT ):

Second solution:

s2 := FileTools:-Text:-ReadFile( "file2.txt" ):

Mathematica/Wolfram Language

Import["filename","String"]

MATLAB / Octave

  fid = fopen('filename','r');
  [str,count] = fread(fid, [1,inf], 'uint8=>char');  % s will be a character array, count has the number of bytes
  fclose(fid);

Mercury

:- module read_entire_file.
:- interface.

:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.
:- import_module string.

main(!IO) :-
   io.open_input("file.txt", OpenResult, !IO),
   (
      OpenResult = ok(File),
      io.read_file_as_string(File, ReadResult, !IO),
      (
           ReadResult = ok(FileContents),
           io.write_string(FileContents, !IO)
      ;
           ReadResult = error(_, IO_Error),
           io.stderr_stream(Stderr, !IO),
           io.write_string(Stderr, io.error_message(IO_Error) ++ "\n", !IO)
      )        
   ;
      OpenResult = error(IO_Error),
      io.stderr_stream(Stderr, !IO),
      io.write_string(Stderr, io.error_message(IO_Error) ++ "\n", !IO)
   ).

Microsoft Small Basic

  v=File.ReadContents(filename)

Nanoquery

import Nanoquery.IO
contents = new(File, "example.txt").readAll()

Neko

/**
 Read entire file
 Tectonics:
   nekoc read-entire-file.neko
   neko read-entire-file
*/

var file_contents = $loader.loadprim("std@file_contents", 1);

try {
  var entire_file = file_contents("read-entire-file.neko");
  $print("Read: ", $ssize(entire_file), " bytes\n");
} catch e {
  $print("Exception: ", e, "\n");
}
Output:
prompt$ nekoc read-entire-file.neko
prompt$ neko read-entire-file.n
Read: 325 bytes

NetRexx

/* NetRexx */
options replace format comments java crossref symbols nobinary

parse arg inFileName .

if inFileName = '' | inFileName = '.' then inFileName = './data/dwarfs.json'
fileContents = slurp(inFileName)
say fileContents

return

-- Slurp a file and return contents as a Rexx string
method slurp(inFileName) public static returns Rexx

  slurped = Rexx null
  slurpStr = StringBuilder()
  ioBuffer = byte[1024]
  inBytes = int 0

  do
    inFile = File(inFileName)
    inFileIS = BufferedInputStream(FileInputStream(inFile))

    loop label ioLoop until inBytes = -1
      slurpStr.append(String(ioBuffer, 0, inBytes))
      inBytes = inFileIS.read(ioBuffer)
      end ioLoop

  catch exFNF = FileNotFoundException
    exFNF.printStackTrace
  catch exIO = IOException
    exIO.printStackTrace
  finally
    do
      inFileIS.close()
    catch ex = IOException
      ex.printStackTrace
    end
  end

  slurped = Rexx(slurpStr.toString)

  return slurped

NewLISP

(read-file "filename")

Nim

To read the content of a file specified by its name:

readFile(filename)

To read the contents of an opened file:

readAll(f)

Objeck

string := FileReader->ReadFile("in.txt");

Objective-C

    /*** 0. PREPARATION    */
    // We need a text file to read; let's redirect a C string to a new file
    // using the shell by way of the stdlib system() function.
    system ("echo \"Hello, World!\" > ~/HelloRosetta");



    /*** 1. THE TASK      */
    // Instantiate an NSString which describes the filesystem location of
    // the file we will be reading.
    NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"HelloRosetta"];
    
    // The selector we're going to use to complete this task,
    // stringWithContentsOfFile:encoding:error, has an optional `error'
    // parameter which can be used to return information about any
    // errors it might run into. It's optional, but we'll create an NSError
    // anyways to demonstrate best practice.
    NSError *anError;
    
    // And finally, the task: read and store the contents of a file as an
    // NSString.
    NSString *aString = [NSString stringWithContentsOfFile:filePath
                                                  encoding:NSUTF8StringEncoding
                                                     error:&anError];

    // If the file read was unsuccessful, display the error description.
    // Otherwise, display the NSString.
    if (!aString) {
        NSLog(@"%@", [anError localizedDescription]);
    } else {
        NSLog(@"%@", aString);
    }

OCaml

For most uses we can use this function:

let load_file f =
  let ic = open_in f in
  let n = in_channel_length ic in
  let s = Bytes.create n in
  really_input ic s 0 n;
  close_in ic;
  (s)

We can replace the last line with the one below if we want to return a type string instead of bytes:

  (Bytes.unsafe_to_string s)

There is no problem reading an entire file with the function really_input because this function is implemented appropriately with an internal loop, but it can only load files which size is equal or inferior to the maximum length of an ocaml string. This maximum size is available with the variable Sys.max_string_length. On 32 bit machines this size is about 16Mo.

To load bigger files several solutions exist, for example create a structure that contains several strings where the contents of the file can be split. Or another solution that is often used is to use a bigarray of chars instead of a string:

type big_string =
  (char, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t

The function below returns the contents of a file with this type big_string, and it does so with "memory-mapping":

let load_big_file filename =
  let fd = Unix.openfile filename [Unix.O_RDONLY] 0o640 in
  let len = Unix.lseek fd 0 Unix.SEEK_END in
  let _ = Unix.lseek fd 0 Unix.SEEK_SET in
  let shared = false in  (* modifications are done in memory only *)
  let bstr = Bigarray.Array1.map_file fd
               Bigarray.char Bigarray.c_layout shared len in
  Unix.close fd;
  (bstr)

Then the length of the data can be get with Bigarray.Array1.dim instead of String.length, and we can access to a given char with the syntactic sugar bstr.{i} (instead of str.[i]) as shown in the small piece of code below (similar to the cat command):

let () =
  let bstr = load_big_file Sys.argv.(1) in
  let len = Bigarray.Array1.dim bstr in
  for i = 0 to pred len do
    let c = bstr.{i} in
    print_char c
  done

Odin

package main

import "core:os"
import "core:fmt"

main :: proc() {
  data, ok := os.read_entire_file("input.txt")
  assert(ok, "Could not open file")
  defer delete(data)

  fmt.print(string(data))
}

Ol

(file->string "filename")

ooRexx

version 1

file = 'c:\test.txt'
myStream = .stream~new(file)
myString = myStream~charIn(,myStream~chars)

Streams are opened on demand and closed when the script finishes. It is possible if you wish to open and close the streams explicitly

file = 'c:\test.txt'
myStream = .stream~new(file)
if mystream~open('read') = 'READY:'
then do
   myString = myStream~charIn(,myStream~chars)
   myStream~close
end

version 2 EXECIO

One can also use EXECIO as it is known from VM/CMS and MVS/TSO:

address hostemu 'execio * diskr "./st.in" (finis stem in.'
Say in.0 'lines in file st.in'
v=''
Do i=1 To in.0
  Say i '>'in.i'<'
  v=v||in.i
  End
say 'v='v
::requires "hostemu" LIBRARY
Output:
E:\>rexx ref
6 lines in file st.in
1 >address hostemu 'execio * diskr "./st.in" (finis stem in.'<
2 >Say in.0<
3 >Do i=1 To in.0<
4 >  Say i '>'in.i'<'<
5 >  End<
6 >::requires "hostemu" LIBRARY<
v=address hostemu 'execio * diskr "./st.in" (finis stem in.'Say in.0Do i=1 To in
.0  Say i '>'in.i'<'  End::requires "hostemu" LIBRARY

Oz

The interface for file operations is object-oriented.

declare
  FileHandle = {New Open.file init(name:"test.txt")}
  FileContents = {FileHandle read(size:all list:$)}
in
  {FileHandle close}
  {System.printInfo FileContents}

FileContents is a list of bytes. The operation does not assume any particular encoding.

Panda

It returns a unicode string of type 'text'.

file:readme.txt .text

PARI/GP

The GP interpreter's ability to read files is extremely limited; reading an entire file is almost all that it can do. The C code PARI library is not similarly limited.

readstr() returns a vector of strings which are the file lines, without newlines. They can be concatenated to make a single string.

str = concat(apply(s->concat(s,"\n"), readstr("file.txt")))

Since readstr() returns strings without newlines there's no way to tell whether the last line had a newline or not. This is fine for its intended use on text files, but not good for reading binary files.

Pascal

See TStrignList example of Delphi

Perl

The modern recommended way, is using one of these CPAN modules:

  • use File::Slurper 'read_text';
    my $text = read_text($filename, $data);
    
  • use Path::Tiny;
    my $text = path($filename)->slurp_utf8;
    
  • use IO::All;
    $text = io($filename)->utf8->all;
    

Traditional ways, without CPAN modules:

  • open my $fh, '<:encoding(UTF-8)', $filename or die "Could not open '$filename':  $!";
    my $text;
    read $fh, $text, -s $filename;
    close $fh;
    
  • my $text;
    {
      local $/ = undef;
      open my $fh, '<:encoding(UTF-8)', $filename or die "Could not open '$filename':  $!";
      $text = <$fh>;
      close $fh;
    }
    
  • my $text = do { local( @ARGV, $/ ) = ( $filename ); <> };
    

For a one-liner from shell, use -0[code]. It normally specifies the oct char code of record separator ($/), so for example perl -n -040 would read chunks of text ending at each space ($/ = ' '). However, -0777 has special meaning: $/ = undef, so the whole file is read in at once (chr 0777 happens to be "ǿ", but Larry doesn't think one should use that as record separator).

perl -n -0777 -e 'print "file len: ".length' stuff.txt

Memory-mapping

use File::Map 'map_file';
map_file(my $str, "foo.txt");
print $str;
use Sys::Mmap;
Sys::Mmap->new(my $str, 0, 'foo.txt')
  or die "Cannot Sys::Mmap->new: $!";
print $str;

File::Map has the advantage of not requiring an explicit munmap(). Its tie is faster than the tie form of Sys::Mmap too.

Phix

Library: Phix/basics
?get_text(command_line()[2])
Output:
"?get_text(command_line()[2])\r\n"

The value returned by get_text is actually a string containing raw binary data (no \r\n -> \n substitution, even when the file is opened in text mode) and is not limited to text files.
There is no builtin method for handling different encodings, but demo\edita handles all such files with ease, including the nifty little encoding drop-down on the open/close dialog.

PHP

Read as string

file_get_contents($filename)

Read as array, one element per line

file($filename)

Picat

The encoding is always UTF-8. Anything more than a small file will cause a buffer overflow.

Works with: Picat
main(Args) =>
    File = Args[1],
    String = read_file_chars(File).

PicoLisp

Using 'till' is the shortest way:

(in "file" (till NIL T))

To read the file into a list of characters:

(in "file" (till NIL))

or, more explicit:

(in "file" (make (while (char) (link @))))

Encoding is always assumed to be UTF-8.

Pike

string content=Stdio.File("foo.txt")->read();

would be the generic way of reading an entire file, but there is also a special function for it:

string content=Stdio.read_file("foo.txt");

PL/I

get file (in) edit ((substr(s, i, 1) do i = 1 to 32767)) (a);

PowerShell

Get-Content foo.txt

This will only detect Unicode correctly with a BOM in place (even for UTF-8). With explicit selection of encoding:

Get-Content foo.txt -Encoding UTF8

However, both return an array of strings which is fine for pipeline use but if a single string is desired the array needs to be joined:

(Get-Content foo.txt) -join "`n"

Prolog

Read a text file. The third argument of read_file_to_string could be options.

Works with: SWI Prolog
:- initialization(main).

main :-
    current_prolog_flag(argv, [File|_]),
    read_file_to_string(File, String, []).

PureBasic

A file can be read with any of the built in commands

Number.b = ReadByte(#File)
Length.i = ReadData(#File, *MemoryBuffer, LengthToRead)
Number.c = ReadCharacter(#File)
Number.d = ReadDouble(#File)
Number.f = ReadFloat(#File)
Number.i = ReadInteger(#File)
Number.l = ReadLong(#File)
Number.q = ReadQuad(#File)
Text$    = ReadString(#File [, Flags])
Number.w = ReadWord(#File)

If the file is s pure text file (no CR/LF etc.), this will work and will read each line untill EOL is found.

If ReadFile(0, "RC.txt")       
  Variable$=ReadString(0)     
  CloseFile(0) 
EndIf

Since PureBasic terminates strings with a #NULL and also split the ReadString() is encountering new line chars, any file containing these must be treated as a data stream.

Title$="Select a file"
Pattern$="Text (.txt)|*.txt|All files (*.*)|*.*"
fileName$ = OpenFileRequester(Title$,"",Pattern$,0)
If fileName$
  If ReadFile(0, fileName$)
    length = Lof(0)     
    *MemoryID = AllocateMemory(length)  
    If *MemoryID
      bytes = ReadData(0, *MemoryID, length)
      MessageRequester("Info",Str(bytes)+" was read")
    EndIf
    CloseFile(0)
  EndIf
EndIf

Python

open(filename).read()

This returns a byte string and does not assume any particular encoding.

In Python 3 strings are in unicode, you can specify encoding when reading:

open(filename, encoding='utf-8').read()

Python docs recommend dealing with files using the with statement:

with open(filename) as f:
    data = f.read()

Starting in Python 3.4, we can use pathlib to reduce boilerplate:

from pathlib import Path

any_string = Path(filename).read_text(encoding='utf-8')
any_binary_data = Path(filename).read_bytes()

Quackery

sharefile takes a file name in a string as an argument, appends a file path if there is one on the ancillary stack filepath, and returns the contents of the file as a string, and 1 (i.e. true) if the file exists. If the file does not exist it returns the name of the file and 0 (i.e. false).

$ "myfile.txt" sharefile

Q

q)file:read0`:file.txt
"First line of file"
"Second line of file"
""

R

fname <- "notes.txt"
contents <- readChar(fname, file.info(fname)$size)

Racket

(file->string "foo.txt")

Raku

(formerly Perl 6)

Works with: Rakudo version 2010.07
my $string = slurp 'sample.txt';

The default encoding is UTF-8. The :enc adverb can be used to specify a different one:

my $string = slurp 'sample.txt', :enc<UTF-16>;

IO::Path objects also provide slurp as a method:

my $string = 'sample.txt'.IO.slurp;

Raven

'myfile.txt' read as $content_as_string

or

'file://r:/home/me/myfile.txt' open as $handle
$handle read as $content_as_string
$handle close

REALbasic

This function accepts a file (FolderItem object) and an optional TextEncoding class. If the TextEncoding is not defined, then REALbasic defaults to UTF-8. Since it is intended for cross-platform development, REALbasic has a number of built-in tools for working with different text encodings, line terminators, etc. [1]

Function readFile(theFile As FolderItem, txtEncode As TextEncoding = Nil) As String
  Dim fileContents As String
  Dim tis As TextInputStream
  tis = tis.Open(theFile)
  fileContents = tis.ReadAll(txtEncode)
  tis.Close
  Return fileContents
  
Exception err As NilObjectException
  MsgBox("File Not Found.")
End Function

REBOL

read %my-file  ; read as text
read/binary %my-file       ; preserve contents exactly

Retro

here 'input.txt file:slurp

REXX

using LINEIN

/*REXX program reads an entire file line-by-line  and  stores it as a continuous string.*/
parse arg iFID .                                 /*obtain optional argument from the CL.*/
if iFID==''  then iFID= 'a_file'                 /*Not specified?  Then use the default.*/
$=                                               /*a string of file's contents (so far).*/
             do  while lines(iFID)\==0           /*read the file's lines until finished.*/
             $=$ || linein(iFID)                 /*append a (file's) line to the string,*/
             end   /*while*/                     /*stick a fork in it,  we're all done. */

using CHARIN

Note that CRLF are in the resulting string.

/*REXX program reads a file and stores it as a continuous character str.*/
Parse Version v
iFID = 'st.in'                         /*name of the input file.        */
If left(v,11)='REXX-Regina' |,
   left(v,11)='REXX-ooRexx' Then Do
  len=chars(iFid)                      /*size of the file               */
  v = charin(iFid,,len)                /*read entire file               */
  End
Else Do                                /* for other Rexx Interpreters   */
  v=''
  Do while chars(iFid)>0               /* read the file chunk by chunk  */
    v=v||charin(iFid,,500)
    End
  End
say 'v='v
say 'length(v)='length(v)
Output:
E:\>rexx refc
v=line 1 of 3
line 2 of 3
line 3 of 3

length(v)=39

Ring

# Read the file
cStr = read("myfile.txt")
# print the file content
See cStr

Also in one line we can read and print the file content.

cStr = read("myfile.txt")   See cStr

We can avoid the string, but it's required in the task.

See read("myfile.txt")

Ruby

IO.read is for text files. It uses the default text encodings, and on Microsoft Windows, it also converts "\r\n" to "\n".

# Read entire text file.
str = IO.read "foobar.txt"

# It can also read a subprocess.
str = IO.read "| grep ftp /etc/services"

Caution! IO.read and File.read take a portname. To open an arbitrary path (which might start with "|"), you must use File.open, then IO#read.

path = "|strange-name.txt"
str = File.open(path) {|f| f.read}

To read a binary file, open it in binary mode.

# Read entire binary file.
str = File.open(path, "rb") {|f| f.read}

Ruby 1.9 can read text files in different encodings.

Works with: Ruby version 1.9
# Read EUC-JP text from file.
str = File.open(path, "r:euc-jp") {|f| f.read}

# Read EUC-JP text from file; transcode text from EUC-JP to UTF-8.
str = File.open(path, "r:euc-jp:utf-8") {|f| f.read}

Run BASIC

open DefaultDir$ + "/public/test.txt" for binary as #f
fileLen = LOF(#f)
a$ = input$(#f, fileLen)
print a$
close #f

Rust

use std::fs::File;
use std::io::Read;

fn main() {
    let mut file = File::open("somefile.txt").unwrap();

    let mut contents: Vec<u8> = Vec::new();
    // Returns amount of bytes read and append the result to the buffer
    let result = file.read_to_end(&mut contents).unwrap();
    println!("Read {} bytes", result);

    // To print the contents of the file
    let filestr = String::from_utf8(contents).unwrap();
    println!("{}", filestr);
}

Scala

Library: Scala
object TextFileSlurper extends App {
  val fileLines =
    try scala.io.Source.fromFile("my_file.txt", "UTF-8").mkString catch {
      case e: java.io.FileNotFoundException => e.getLocalizedMessage()
    }
}

Scheme

Uses SRFI-13:

(with-input-from-file "foo.txt"
  (lambda ()
    (reverse-list->string
     (let loop ((char (read-char))
                (result '()))
       (if (eof-object? char)
           result
           (loop (read-char) (cons char result)))))))

Works with Chicken Scheme:

(with-input-from-file "foo.txt" read-string)

In GNU Guile, with decoding into Unicode code points:

(use-modules (ice-9 textual-ports))
(call-with-input-file "foo.txt" get-string-all)

Seed7

The library getf.s7i defines the function getf, which reads a whole file into a string:

$ include "seed7_05.s7i";
  include "getf.s7i";

const proc: main is func
  local
    var string: fileContent is "";
  begin
    fileContent := getf("text.txt");
  end func;

SenseTalk

Put file "~/Documents/myFile.txt" into  TestFile
put testFile

Sidef

Reading an entire file as a string, can be achieved with the FileHandle.slurp() method, as illustrated bellow:

var file = File.new(__FILE__);
var content = file.open_r.slurp;
print content;

Starting with version 2.30, File.read() can do the same:

var file = File(__FILE__)
var content = file.read(:utf8)
print content

Smalltalk

Works with: Pharo
(StandardFileStream oldFileNamed: 'foo.txt') contents
Works with: Smalltalk/X
'foo.txt' asFilename contentsAsString

SNOBOL4

In SNOBOL4, file I/O is done by associating a variable with the desired file, via the input() built-in function. After the association, each reference to the named variable provides as the variable's value the next block or line of data from the corresponding file. The exact format of the input() function parameters tends to vary based on the implementation in use. In this example, the code reads the file in blocks of 512k bytes (or less) until the entire file has been read into one long string in memory.

      input(.inbin,21,"filename.txt [-r524288]")     :f(end)
rdlp  buf = inbin                                    :s(rdlp)
*
*  now process the 'buf' containing the file
*
end

Sparkling

let contents = readfile("foo.txt");

SPL

text = #.readtext("filename.txt")

Standard ML

(* string -> string *)
fun readFile path =
  (fn strm =>
    TextIO.inputAll strm before TextIO.closeIn strm) (TextIO.openIn path)

</syntaxhighlight>

Stata

It's possible to get the entire content as an array of lines with cat. However, here we want a single string. See fopen and related functions.

mata
f = fopen("somedata.txt", "r")
fseek(f, 0, 1)
n = ftell(f)
fseek(f, 0, -1)
s = fread(f, n)
fclose(f)
end

Swift

Works with: Swift version 1
import Foundation

let path = "~/input.txt".stringByExpandingTildeInPath
if let string = String(contentsOfFile: path, encoding: NSUTF8StringEncoding) {
  println(string) // print contents of file
}
Works with: Swift version 5
import Foundation

let path = "input.txt"
do
{
	let string = try String(contentsOfFile: path, encoding: String.Encoding.utf8)
	print(string) // print contents of file
}
catch
{
	print("error occured: \(error)")
}

Tcl

This reads the data in as text, applying the default encoding translations.

set f [open $filename]
set data [read $f]
close $f

To read the data in as uninterpreted bytes, either use fconfigure to put the handle into binary mode before reading, or (from Tcl 8.5 onwards) do this:

set f [open $filename "rb"]
set data [read $f]
close $f

TUSCRIPT

$$ MODE TUSCRIPT
ERROR/STOP OPEN ("rosetta.txt",READ,-std-)
var=FILE ("rosetta.txt")

TXR

@(next "foo.txt")
@(freeform)
@LINE

The freeform directive in TXR causes the remaining lines of the text stream to be treated as one big line, catenated together. The default line terminator is the newline "\n". This lets the entire input be captured into a single variable as a whole-line match.

UNIX Shell

We start a 'cat' process to read the entire file, and use '$(...)' to grab the output of 'cat'. We use 'printf' which might be more portable than 'echo'. Because '$(...)' can chop off a newline at the end of the file, we tell 'printf' to add an extra newline.

f=`cat foo.txt`    # f will contain the entire contents of the file
printf '%s\n' "$f"
f=$(cat foo.txt)
printf '%s\n' "$f"

Some shells provide a shortcut to read a file without starting a 'cat' process.

Works with: bash
Works with: pdksh
f=$(<foo.txt)
echo -E "$f"
Works with: zsh
file=$(<foo.txt)
print $file

alternatively

zmodload zsh/mapfile
print $mapfile[foo.txt]

Ursa

decl string contents
decl file f
f.open "filename.txt"
set contents (f.readall)

Vala

string file_contents;
FileUtils.get_contents("foo.txt", out file_contents);

VBScript

Read text file with default encoding into variable and display

dim s
s = createobject("scripting.filesystemobject").opentextfile("slurp.vbs",1).readall
wscript.echo s

Read text file with UTF-16 encoding into memory and display

wscript.echo createobject("scripting.filesystemobject").opentextfile("utf16encoded.txt",1,-1).readall

Vedit macro language

In Vedit Macro Language, a "string variable" can be either an edit buffer or a text register.
Text registers can hold only a limited amount of data (about 120 KB each in current version).
Edit buffers can handle files of unlimited size (even larger than the size of virtual memory). For large files, only a part of the file is kept in memory, but from users point of view there is no practical difference to having the whole file in memory.

Read file into edit buffer. The buffer is allocated automatically:

File_Open("example.txt")

Read file into text register 10:

Reg_Load(10, "example.txt")

Visual Basic

Works with: Visual Basic version 5
Works with: Visual Basic version 6
Declare Function MultiByteToWideChar Lib "kernel32.dll" ( _
     ByVal CodePage As Long, _
     ByVal dwFlags As Long, _
     ByVal lpMultiByteStr As Long, _
     ByVal cchMultiByte As Long, _
     ByVal lpWideCharStr As Long, _
     ByVal cchWideChar As Long) As Long
Const CP_UTF8 As Long = 65001

Sub Main()
Dim fn As Integer
Dim i As Long
Dim b() As Byte
Dim s As String

  fn = FreeFile()
  Open "c:\test.txt" For Binary Access Read As #fn
  ReDim b(0 To (LOF(fn) - 1))
  Get #fn, 1, b()
  
  If b(0) = &HFF And b(1) = &HFE Then
  'UTF-16, little-endian
    ReDim b(0 To (LOF(fn) - 3))
    Get #fn, 3, b()
    s = b()
  ElseIf b(0) = &HEF And b(1) = &HBB And b(2) = &HBF Then
  'UTF-8
    i = MultiByteToWideChar(CP_UTF8, 0&, VarPtr(b(3)), LOF(fn) - 3, StrPtr(s), 0)
    s = Space$(i)
    i = MultiByteToWideChar(CP_UTF8, 0&, VarPtr(b(3)), LOF(fn) - 3, StrPtr(s), Len(s))
  Else
  'assume ANSI
    s = StrConv(b(), vbUnicode)
  End If
  Close #fn
  Debug.Print s
End Sub

Visual Basic .NET

Imports System.IO

Public Class Form1

  ' Read all of the lines of a file.
  ' Function assumes that the file exists.
  Private Sub ReadLines(ByVal FileName As String)

    Dim oReader As New StreamReader(FileName)
    Dim sLine As String = oReader.ReadToEnd()

    oReader.Close()

  End Sub

End Class

Wart

with infile "x"
  with outstring
    whilet line (read_line)
      prn line

Wren

Wren's File.Read(path) static method reads the entire contents of the file at path and returns it as a string.

As per the documentation: "No encoding or decoding is done. If the file is UTF-8, then the resulting string will be a UTF-8 string. Otherwise, it will be a string of bytes in whatever encoding the file uses."

For the following script, a file called "input.txt" has been created which contains the string "abcdefghijklmnopqrstuvwxyz".

import "io" for File

System.print(File.read("input.txt"))
Output:
abcdefghijklmnopqrstuvwxyz

XPL0

This example reads its own source code file and displays it as a string. The command line is: readfile <readfile.xpl

include c:\cxpl\codes;  \intrinsic 'code' declarations
string 0;               \use zero-terminated string convention
int  I;
char Str;
[Str:= GetHp;           \starting address of block of local "heap" memory
I:= 0;                  \ [does the exact same thing as Reserve(0)]
loop    [Str(I):= ChIn(1);
        if Str(I) = $1A\EOF\ then [Str(I):= 0;  quit];
        I:= I+1;
        ];
SetHp(Str+I+1);         \set heap pointer beyond Str (not really needed here)
Text(0, Str);           \show file as a string
]
Output:
include c:\cxpl\codes;  \intrinsic 'code' declarations
string 0;               \use zero-terminated string convention
int  I;
char Str;
[Str:= GetHp;           \starting address of block of local "heap" memory
I:= 0;                  \ [does the exact same thing as Reserve(0)]
loop    [Str(I):= ChIn(1);
        if Str(I) = $1A\EOF\ then [Str(I):= 0;  quit];
        I:= I+1;
        ];
SetHp(Str+I+1);         \set heap pointer beyond Str (not really needed here)
Text(0, Str);           \show file as a string
]

Xtend

package com.rosetta.example

import java.io.File
import java.io.PrintStream

class ReadFile {
    def static main( String ... args ) {
        val content = new String(Files.readAllBytes(Paths.get("file.txt")))
    }
}

Yorick

This loads foo.txt into lines as an array of strings. Each array element is one line. Each line's trailing newline is removed.

lines = rdfile("foo.txt");

This loads foo.txt into content as a single scalar string, without losing newlines.

f = open("foo.txt", "rb");
raw = array(char, sizeof(f));
_read, f, 0, raw;
close, f;
content = strchar(raw);

Zig

Works with: Zig version 0.10.x
Works with: Zig version 0.11.x
Works with: Zig version 0.12.0-dev.1604+caae40c21
const std = @import("std");

const File = std.fs.File;

pub fn main() (error{OutOfMemory} || File.OpenError || File.ReadError)!void {
    var gpa: std.heap.GeneralPurposeAllocator(.{}) = .{};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    const cwd = std.fs.cwd();

    var file = try cwd.openFile("input_file.txt", .{ .mode = .read_only });
    defer file.close();

    const file_content = try file.readToEndAlloc(allocator, comptime std.math.maxInt(usize));
    defer allocator.free(file_content);

    std.debug.print("Read {d} octets. File content:\n", .{file_content.len});
    std.debug.print("{s}", .{file_content});
}

Using mmap

When linking libc, will use libc mmap (or mmap64) call. Otherwise uses namespace supplied by user or std (includes support for Windows, among other things, so no need to write two separate versions like in C).

const std = @import("std");

const File = std.fs.File;

pub fn main() (File.OpenError || File.SeekError || std.os.MMapError)!void {
    const cwd = std.fs.cwd();

    var file = try cwd.openFile("input_file.txt", .{ .mode = .read_only });
    defer file.close();

    const file_size = (try file.stat()).size;

    const file_content = try std.os.mmap(null, file_size, std.os.PROT.READ, std.os.MAP.PRIVATE, file.handle, 0);
    defer std.os.munmap(file_content);

    std.debug.print("Read {d} octets. File content:\n", .{file_content.len});
    std.debug.print("{s}", .{file_content});
}

zkl

data := File("foo.txt","r").read()

The file parameters are the same as C's