Read entire file: Difference between revisions

m
 
(26 intermediate revisions by 18 users not shown)
Line 20:
{{trans|Python}}
 
<syntaxhighlight lang ="11l">File(filename).read()</langsyntaxhighlight>
 
=={{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"
<langsyntaxhighlight lang="forth">
"somefile.txt" f:slurp >s
</syntaxhighlight>
</lang>
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">proc MAIN()
char array STRING
open (1,"D:FILE.TXT",4,0)
Line 36:
return
 
</syntaxhighlight>
</lang>
 
=={{header|Ada}}==
Line 47:
and then Ada.Direct_IO to read the whole file in one chunk:
 
<langsyntaxhighlight Adalang="ada">with Ada.Directories,
Ada.Direct_IO,
Ada.Text_IO;
Line 69:
 
Ada.Text_IO.Put (Contents);
end Whole_File;</langsyntaxhighlight>
 
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:
Mapping the whole file into the address space of your process and then overlaying the file with a String object.
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO,
POSIX.IO,
POSIX.Memory_Mapping,
Line 113:
Length => Text_Size);
Close (File => Text_File);
end Read_Entire_File;</langsyntaxhighlight>
 
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:
 
'''In official/standard ALGOL 68 only:'''
<langsyntaxhighlight lang="algol68">MODE BOOK = FLEX[0]FLEX[0]FLEX[0]CHAR; ¢ pages of lines of characters ¢
BOOK book;
 
Line 138:
INT errno = open(book file, "book.txt", stand in channel);
 
get(book file, book)</langsyntaxhighlight>
 
Once a "book" has been read into a '''book''' array it can still be associated
Line 147:
 
'''In official/standard ALGOL 68 only:'''
<langsyntaxhighlight lang="algol68">FILE cached book file;
associate(cached book file, book)</langsyntaxhighlight>
 
=={{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>For now, only a simple version is shown.</p>
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#include <hopper.h>
 
Line 161:
println ( "File loaded:\n",s )
exit(0)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 175:
 
=={{header|AppleScript}}==
<langsyntaxhighlight AppleScriptlang="applescript">set pathToTextFile to ((path to desktop folder as string) & "testfile.txt")
 
-- short way: open, read and close in one step
Line 183:
set fileRef to open for access pathToTextFile
set fileContent to read fileRef
close access fileRef</langsyntaxhighlight>
 
=={{header|Arturo}}==
<langsyntaxhighlight lang="rebol">contents: read "input.txt"</langsyntaxhighlight>
 
=={{header|ATS}}==
There are various functions in the ATS prelude, including this one that is based on fread(3) and returns Strptr1:
<langsyntaxhighlight lang="ats">val s = fileref_get_file_string (stdin_ref)</langsyntaxhighlight>
Because Strptr1 is a NUL-terminated string, fileref_get_file_string cannot be used for data that contains bytes equal to zero.
 
=={{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.</langsyntaxhighlight>
This script works fine as-is provided C:\filename.txt exists.
 
=={{header|AutoIt}}==
<syntaxhighlight lang="autoit">
<lang AutoIt>
$fileOpen = FileOpen("file.txt")
$fileRead = FileRead($fileOpen)
FileClose($fileOpen)
</syntaxhighlight>
</lang>
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">#!/usr/bin/awk -f
BEGIN {
## empty record separate,
Line 218:
## no further line is read printed
print "=== line "NR,":",$0;
}</langsyntaxhighlight>
 
{{works with|gawk}}
<langsyntaxhighlight lang="awk">
#!/usr/bin/awk -f
 
Line 232:
 
}
</syntaxhighlight>
</lang>
 
=={{header|BaCon}}==
For string data:
 
<langsyntaxhighlight lang="qbasic">content$ = LOAD$(filename$)</langsyntaxhighlight>
 
For memory mapped binary data:
 
<langsyntaxhighlight lang="freebasic">binary = BLOAD("somefile.bin")
PRINT "First two bytes are: ", PEEK(binary), " ", PEEK(binary+1)
FREE binary</langsyntaxhighlight>
 
=={{header|BASIC}}==
Line 251:
{{works with|QBasic}}
 
<langsyntaxhighlight lang="qbasic">DIM f AS STRING
OPEN "file.txt" FOR BINARY AS 1
f = SPACE$(LOF(1))
GET #1, 1, f
CLOSE 1</langsyntaxhighlight>
 
==={{header|Applesoft BASIC}}===
<syntaxhighlight lang="gwbasic"> 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$</syntaxhighlight>
==={{header|Commodore BASIC}}===
<langsyntaxhighlight 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
30 rem ================================
Line 271 ⟶ 287:
120 next
130 close 4
140 end</langsyntaxhighlight>
 
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">f = freefile
open f, "input.txt"
while not eof(f)
linea$ = readline(f)
print linea$
end while
close f</syntaxhighlight>
 
==={{header|OxygenBasic}}===
Two Formats:
<syntaxhighlight lang="text">
 
string s
 
'AS FUNCTION
s=GetFile "t.txt"
 
'AS PROCEDURE
Getfile "t.txt",s
 
</syntaxhighlight>
 
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">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</syntaxhighlight>
 
==={{header|Yabasic}}===
<syntaxhighlight lang="yabasic">open "input.txt" for reading as #1
while not eof(1)
line input #1 linea$
print linea$
wend
close #1</syntaxhighlight>
Or also
<syntaxhighlight lang="yabasic">a = open("input.txt")
while not eof(a)
line input #a linea$
print linea$
wend</syntaxhighlight>
 
=={{header|BBC BASIC}}==
In [[BBC BASIC for Windows]] and [[Brandy BASIC]] the maximum string length is 65535 characters.
<langsyntaxhighlight lang="bbcbasic"> file% = OPENIN("input.txt")
strvar$ = ""
WHILE NOT EOF#file%
strvar$ += CHR$(BGET#file%)
ENDWHILE
CLOSE #file%</langsyntaxhighlight>
API version:
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> file% = OPENIN("input.txt")
strvar$ = STRING$(EXT#file%, " ")
SYS "ReadFile", @hfile%(file%), !^strvar$, EXT#file%, ^temp%, 0
CLOSE #file%</langsyntaxhighlight>
 
=={{header|Blue}}==
 
Linux/x86-64. Reads the entire file via the mmap system call.
 
<syntaxhighlight lang="blue">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
;
</syntaxhighlight>
 
=={{header|BQN}}==
 
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].
 
<syntaxhighlight lang="bqn">•file.Chars "file"
•file.Bytes "file"
 
# Shorthands:
•FChars "file"
•FBytes "file"
</syntaxhighlight>
 
<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.
 
=={{header|Bracmat}}==
Line 293 ⟶ 422:
=={{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.
<langsyntaxhighlight lang="bf">> 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</langsyntaxhighlight>
{{out}}
<pre>$ curl -Ls rosettacode.org | bf ">,[>,]<[<]>[.>]"
Line 305 ⟶ 434:
 
=={{header|Brat}}==
<langsyntaxhighlight lang="brat">include :file
 
file.read file_name</langsyntaxhighlight>
 
=={{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>)
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 338 ⟶ 467:
}
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
=== Memory map ===
Line 345 ⟶ 474:
We can memory-map the file.
 
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
Line 373 ⟶ 502:
close(fd);
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
{{works with|Windows}}
Line 379 ⟶ 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.
 
<langsyntaxhighlight lang="c">#include <windows.h>
#include <stdio.h>
 
Line 397 ⟶ 526:
CloseHandle(hFile);
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
{{works with|C sharp|3.0}}
 
<langsyntaxhighlight lang="csharp">using System.IO;
 
class Program
Line 411 ⟶ 540:
// Can optionally take a second parameter to specify the encoding, e.g. File.ReadAllText("c:\\autoexec.bat", Encoding.UTF8)
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight Cpplang="cpp">#include <iostream>
#include <fstream>
#include <string>
Line 437 ⟶ 566:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Clojure}}==
The core function ''slurp'' does the trick; you can specify an encoding as an optional second argument:
<langsyntaxhighlight lang="clojure">(slurp "myfile.txt")
(slurp "my-utf8-file.txt" "UTF-8")</langsyntaxhighlight>
 
=={{header|CMake}}==
Sets a variable named ''string''.
 
<langsyntaxhighlight lang="cmake">file(READ /etc/passwd string)</langsyntaxhighlight>
 
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 453 ⟶ 582:
The only way to read binary files is to use the ''HEX'' keyword to convert the entire file to a hexadecimal string.
 
<langsyntaxhighlight lang="cmake">file(READ /etc/pwd.db string HEX)</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
The following will read and store the file as a sequence of bytes.
 
<langsyntaxhighlight lang="lisp">(defun file-string (path)
(with-open-file (stream path)
(let ((data (make-string (file-length stream))))
(read-sequence data stream)
data)))</langsyntaxhighlight>
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 468 ⟶ 597:
The simplest way to read an entire file to a string is by using File.read:
 
<langsyntaxhighlight lang="ruby">content = File.read("input.txt")
puts content</langsyntaxhighlight>
 
{{out}}
Line 476 ⟶ 605:
The encoding is UTF-8 by default, but it can be explicitly specified:
 
<langsyntaxhighlight lang="ruby">content = File.read("input.txt", "UTF-16")</langsyntaxhighlight>
 
or
 
<langsyntaxhighlight lang="ruby">content = File.read("input.txt", encoding: "UTF-16")</langsyntaxhighlight>
 
File.open allows for more options and closes the file implicitly. Combine it with File#gets_to_end to read the entire file:
 
<langsyntaxhighlight lang="ruby">content = File.open("input.txt") do |file|
file.gets_to_end
end</langsyntaxhighlight>
 
Or no implicit closing at all with File.new:
 
<langsyntaxhighlight lang="ruby">file = File.new("input.txt")
content = file.gets_to_end
file.close</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.file: read, readText;
 
void main() {
Line 503 ⟶ 632:
// To read a whole file into a validated UTF-8 string:
string txt = readText("unixdict.txt");
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
Using TStringList
 
<langsyntaxhighlight Delphilang="delphi">program ReadAll;
 
{$APPTYPE CONSOLE}
Line 529 ⟶ 658:
lList.Free;
end;
end.</langsyntaxhighlight>
 
 
'''Works with''': Delphi 2010 and above
 
<langsyntaxhighlight Delphilang="delphi">program ReadAll;
 
{$APPTYPE CONSOLE}
Line 547 ⟶ 676:
Writeln(TFile.ReadAllText('C:\autoexec.bat', TEncoding.ASCII));
Readln;
end.</langsyntaxhighlight>
 
=={{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>.
<langsyntaxhighlight lang="dejavu">local :filecontents !decode!utf-8 !read "file.txt"</langsyntaxhighlight>
 
=={{header|E}}==
 
<langsyntaxhighlight lang="e"><file:foo.txt>.getText()</langsyntaxhighlight>
 
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}}==
Line 563 ⟶ 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.
 
<syntaxhighlight lang="elixir">
<lang Elixir>
defmodule FileReader do
# Read in the file
Line 587 ⟶ 742:
end
end
</syntaxhighlight>
</lang>
 
=={{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.)
 
<langsyntaxhighlight Lisplang="lisp">(setq my-variable (with-temp-buffer
(insert-file-contents "foo.txt")
(buffer-string)))</langsyntaxhighlight>
 
(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}}==
<langsyntaxhighlight lang="erlang">{ok, B} = file:read_file("myfile.txt").</langsyntaxhighlight>
 
This reads the entire file into a binary object.
Line 607 ⟶ 762:
The openEuphoria team is/was working on supporting it. It may have been implemented by now.''
 
<langsyntaxhighlight lang="euphoria">
function load_file(sequence filename)
integer fn,c
Line 624 ⟶ 779:
return data
end function
</syntaxhighlight>
</lang>
 
=={{header|F Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">// 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)</langsyntaxhighlight>
 
=={{header|Factor}}==
 
<langsyntaxhighlight lang="factor">USING: io.encodings.ascii io.encodings.binary io.files ;
 
! to read entire file as binary
Line 640 ⟶ 795:
 
! to read entire file as lines of text
"foo.txt" ascii file-lines</langsyntaxhighlight>
 
=={{header|Fantom}}==
Provide the filename to read from as a command-line parameter.
<langsyntaxhighlight lang="fantom">
class ReadString
{
Line 653 ⟶ 808:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Forth}}==
{{works with|GNU Forth}}
<langsyntaxhighlight lang="forth">s" foo.txt" slurp-file ( str len )</langsyntaxhighlight>
 
=={{header|Fortran}}==
Line 663 ⟶ 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.
 
<langsyntaxhighlight lang="fortran">program read_file
implicit none
integer :: n
Line 676 ⟶ 831:
print "(A)", s
end program</langsyntaxhighlight>
 
=== 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.
 
<langsyntaxhighlight lang="fortran">program file_win
use kernel32
use iso_c_binding
Line 702 ⟶ 857:
s = CloseHandle(hMap)
s = CloseHandle(hFile)
end program</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Open "input.txt" For Input Encoding "ascii" As #1
Line 714 ⟶ 869:
buffer = "" '' release memory used by setting buffer to empty
Close #1
Sleep</langsyntaxhighlight>
 
=={{header|Frink}}==
The read[URL] function reads the entire contents of a URL. The encoding can be specified if necessary.
<langsyntaxhighlight lang="frink">
a = read["file:yourfile.txt"]
b = read["file:yourfile.txt", "UTF-8"]
</syntaxhighlight>
</lang>
 
=={{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.
<syntaxhighlight lang="futurebasic">_window = 1
begin enum 1
_scrollView
_textView
end enum
 
void local fn BuildWindow
Note: This code goes beyond simply specifying the file to open. It includes a dialog window 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 console window with automatic save as, copy and paste, select all and undo commands. (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.
CGRect r = {0,0,550,400}
<lang futurebasic>
window _window, @"Read Entire File", r
include "ConsoleWindow"
scrollview _scrollView, r
ViewSetAutoresizingMask( _scrollView, NSViewWidthSizable + NSViewHeightSizable )
textview _textView,, _scrollView
end fn
 
local fn ReadTextFile
CFStringRef string
dim as CFURLRef fileRef
CFURLRef url = openpanel 1, @"Select text file..."
dim as Handle h
if ( url )
dim as CFStringRef cfStr : cfStr = NULL
string = fn StringWithContentsOfURL( url, NSUTF8StringEncoding, NULL )
dim as long fileLen
TextSetString( _textView, string )
 
else
if ( files$( _CFURLRefOpen, "TEXT", "Select text file...", @fileRef ) )
open "i",// 2,user fileRefcancelled
end if
fileLen = lof( 2, 1 )
h = fn NewHandleClear( fileLen )
if ( h )
read file 2, [h], fileLen
close #2
cfStr = fn CFStringCreateWithBytes( _kCFAllocatorDefault, #[h], fn GetHandleSize(h), _kCFStringEncodingMacRoman, _false )
fn DisposeH( h )
end if
else
// User canceled
end if
 
fn HIViewSetText( sConsoleHITextView, cfStr )
CFRelease( cfStr )
end fn
 
fn BuildWindow
fn ReadTextFile
</lang>
This can be shortened considerably by wrapping Objective-C code:
<pre>
include "ConsoleWindow"
 
HandleEvents</syntaxhighlight>
local fn ReadTextFile
dim as CFURLRef fileRef
dim as CFStringRef cfStr : cfStr = NULL
 
if ( files$( _CFURLRefOpen, "TEXT", "Select text file...", @fileRef ) )
BeginCCode
cfStr = (CFStringRef)[[NSString alloc] initWithContentsOfURL:(NSURL *)fileRef encoding:NSUTF8StringEncoding error:nil];
EndC
fn HIViewSetText( sConsoleHITextView, cfStr )
CFRelease( cfStr )
else
// User canceled
end if
end fn
fn ReadTextFile
</pre>
 
=={{header|Gambas}}==
<langsyntaxhighlight lang="gambas">Public Sub Form_Open()
Dim sFile As String
 
sFile = File.Load(User.home &/ "file.txt")
 
End</langsyntaxhighlight>
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">InputTextFile("input.txt");
s := ReadAll(f);; # two semicolons to hide the result, which may be long
CloseStream(f);</langsyntaxhighlight>
 
=={{header|Genie}}==
<langsyntaxhighlight lang="genie">[indent=4]
/*
Read entire file, in Genie
Line 811 ⟶ 944:
return
 
stdout.printf("%d bytes read from %s\n", fileContents.length, fileName)</langsyntaxhighlight>
 
{{out}}
Line 827 ⟶ 960:
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.
<langsyntaxhighlight lang="go">import "io/ioutil"
 
data, err := ioutil.ReadFile(filename)
sv := string(data)</langsyntaxhighlight>
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 <tt>syscall.Mmap</tt>, another source file with the opposite build constraint could use <tt>ioutil.ReadFile</tt> as above).
<langsyntaxhighlight lang="go">// +build !windows,!plan9,!nacl // These lack syscall.Mmap
 
package main
Line 860 ⟶ 993:
}
fmt.Println(string(data))
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def fileContent = new File("c:\\file.txt").text</langsyntaxhighlight>
 
=={{header|GUISS}}==
 
<langsyntaxhighlight lang="guiss">Start,Programs,Accessories,Notepad,Menu:File,Open,Doubleclick:Icon:Notes.TXT,Button:OK</langsyntaxhighlight>
 
=={{header|Haskell}}==
In the IO monad:
 
<langsyntaxhighlight lang="haskell">do text <- readFile filepath
-- do stuff with text</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight lang="haskell">eagerReadFile :: FilePath -> IO String
eagerReadFile filepath = do
text <- readFile filepath
last text `seq` return text</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
The first code snippet below reads from stdin directly into the string fs,
preserving line separators (if any) and reading in large chunks.
<langsyntaxhighlight Iconlang="icon">every (fs := "") ||:= |reads(1000000)</langsyntaxhighlight>
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.
<langsyntaxhighlight Iconlang="icon">every put(fL := [],|FUNC(read()))
every (fs := "") ||:= !fL || "\n"
fL := &null</langsyntaxhighlight>
 
=={{header|Inform 7}}==
Line 895 ⟶ 1,028:
 
{{works with|Glulx virtual machine}}
<langsyntaxhighlight lang="inform7">Home is a room.
 
The File of Testing is called "test".
Line 901 ⟶ 1,034:
When play begins:
say "[text of the File of Testing]";
end the story.</langsyntaxhighlight>
 
=={{header|J}}==
 
<langsyntaxhighlight lang="j"> require 'files' NB. not needed for J7 & later
var=: freadsfread 'foo.txt'</langsyntaxhighlight>
 
To memory map the file:
 
<langsyntaxhighlight lang="j"> require 'jmf'
JCHAR map_jmf_ 'var';'foo.txt'</langsyntaxhighlight>
 
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}}==
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.
<langsyntaxhighlight lang="java">import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
Line 938 ⟶ 1,085:
return contents.toString();
}
}</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight lang="java">
import java.nio.channels.FileChannel.MapMode;
import java.nio.MappedByteBuffer;
Line 962 ⟶ 1,109:
return buffer;
}
}</langsyntaxhighlight>
 
or one can take a shortcut:
<langsyntaxhighlight lang="java">String content = new Scanner(new File("foo"), "UTF-8").useDelimiter("\\A").next();</langsyntaxhighlight>
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+}}
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>:
<langsyntaxhighlight lang="java5">import java.util.List;
import java.nio.charset.Charset;
import java.nio.file.*;
Line 984 ⟶ 1,131:
return Files.readAllBytes(file);
}
}</langsyntaxhighlight>
 
{{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}}==
This works in IExplorer or a standalone js file. Note the similarity to the VBScript code.
<langsyntaxhighlight lang="javascript">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)}</langsyntaxhighlight>
 
The following works in all browsers, including IE10.
<langsyntaxhighlight lang="javascript">var file = document.getElementById("fileInput").files.item(0); //a file input element
if (file) {
var reader = new FileReader();
Line 1,009 ⟶ 1,169:
alert(event);
}
</syntaxhighlight>
</lang>
 
=={{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:
<langsyntaxhighlight lang="sh">jq -R -s . input.txt</langsyntaxhighlight>
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:<langsyntaxhighlight lang="sh">jq -R . input.txt | jq -s .</langsyntaxhighlight>
Equivalently:<langsyntaxhighlight lang="sh">jq -R -s 'split("\n")' input.txt </langsyntaxhighlight>
 
Other cases can be similarly handled.
 
=={{header|Jsish}}==
<langsyntaxhighlight lang="javascript">var contents = File.read("filename")</langsyntaxhighlight>
 
From the shell:
Line 1,041 ⟶ 1,201:
=={{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).
<langsyntaxhighlight Julialang="julia">read("/devel/myfile.txt", String) # read file into a string</langsyntaxhighlight>
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:
<langsyntaxhighlight Julialang="julia">A = Mmap.mmap(open("/devel/myfile.txt"), Array{UInt8,1})</langsyntaxhighlight>
 
=={{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}}==
 
The built-in function <code>io:readFile</code> will read the entire content of the file as a string:
 
<langsyntaxhighlight lang="kap">content ← io:readFile "file.txt"</langsyntaxhighlight>
 
The function <code>io:read</code> can be used to return all the lines in the file as an array:
 
<langsyntaxhighlight lang="kap">content ← io:read "file.txt"</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">import java.io.File
 
fun main(args: Array<String>) {
println(File("unixdict.txt").readText(charset = Charsets.UTF_8))
}</langsyntaxhighlight>
 
=={{header|LabVIEW}}==
Line 1,066 ⟶ 1,231:
 
=={{header|Lang5}}==
<syntaxhighlight lang ="lang5">'foo.txt slurp</langsyntaxhighlight>
 
=={{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.
 
<langsyntaxhighlight Lassolang="lasso ">local(f) = file('foo.txt')
#f->readString</langsyntaxhighlight>
 
=={{header|LFE}}==
 
<langsyntaxhighlight lang="lisp">
(set `#(ok ,data) (file:read_file "myfile.txt"))
</syntaxhighlight>
</lang>
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb">filedialog "Open a Text File","*.txt",file$
if file$<>"" then
open file$ for input as #1
Line 1,087 ⟶ 1,252:
close #1
print entire$
end if</langsyntaxhighlight>
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">----------------------------------------
-- Reads whole file, returns string
-- @param {string} tFile
Line 1,102 ⟶ 1,267:
fp.closeFile()
return res
end</langsyntaxhighlight>
 
=={{header|LiveCode}}==
Line 1,109 ⟶ 1,274:
 
Using URL
<langsyntaxhighlight LiveCodelang="livecode">put URL "file:///usr/share/dict/words" into tVar
put the number of lines of tVar</langsyntaxhighlight>
 
Using file open + read + close
<langsyntaxhighlight LiveCodelang="livecode">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</langsyntaxhighlight>
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">
<lang Lua>
--If the file opens with no problems, io.open will return a
--handle to the file with methods attached.
Line 1,143 ⟶ 1,308:
--garbage collected.
file:close()
</syntaxhighlight>
</lang>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module checkit {
\\ prepare a file
Line 1,167 ⟶ 1,332:
}
checkit
</syntaxhighlight>
</lang>
 
=={{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.
 
<langsyntaxhighlight lang="m4">define(`foo',include(`file.txt'))
defn(`foo')
defn(`foo')</langsyntaxhighlight>
 
=={{header|Make}}==
{{works with|GNU make}}
<langsyntaxhighlight Makelang="make">contents := $(shell cat foo.txt)</langsyntaxhighlight>
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}}==
First solution:
<syntaxhighlight lang="maple">
<lang Maple>
s1 := readbytes( "file1.txt", infinity, TEXT ):
</syntaxhighlight>
</lang>
Second solution:
<syntaxhighlight lang="maple">
<lang Maple>
s2 := FileTools:-Text:-ReadFile( "file2.txt" ):
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Import["filename","String"]</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight MATLABlang="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
fclose(fid); </langsyntaxhighlight>
 
=={{header|Mercury}}==
<langsyntaxhighlight Mercurylang="mercury">:- module read_entire_file.
:- interface.
 
Line 1,226 ⟶ 1,391:
io.stderr_stream(Stderr, !IO),
io.write_string(Stderr, io.error_message(IO_Error) ++ "\n", !IO)
).</langsyntaxhighlight>
 
=={{header|Microsoft Small Basic}}==
<langsyntaxhighlight lang="smallbasic"> v=File.ReadContents(filename) </langsyntaxhighlight>
 
=={{header|Nanoquery}}==
<langsyntaxhighlight Nanoquerylang="nanoquery">import Nanoquery.IO
contents = new(File, "example.txt").readAll()</langsyntaxhighlight>
 
=={{header|Neko}}==
<syntaxhighlight lang="actionscript">/**
<lang ActionScript>/**
Read entire file
Tectonics:
Line 1,250 ⟶ 1,415:
} catch e {
$print("Exception: ", e, "\n");
}</langsyntaxhighlight>
 
{{out}}
Line 1,258 ⟶ 1,423:
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,301 ⟶ 1,466:
 
return slurped
</syntaxhighlight>
</lang>
 
=={{header|NewLISP}}==
<langsyntaxhighlight NewLISPlang="newlisp">(read-file "filename")</langsyntaxhighlight>
 
=={{header|Nim}}==
To read the content of a file specified by its name:
<syntaxhighlight lang Nim="nim">readFile(filename)</langsyntaxhighlight>
To read the contents of an opened file:
<syntaxhighlight lang="text">readAll(f)</langsyntaxhighlight>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
string := FileReader->ReadFile("in.txt");
</syntaxhighlight>
</lang>
 
=={{header|Objective-C}}==
<langsyntaxhighlight lang="objc">
/*** 0. PREPARATION */
// We need a text file to read; let's redirect a C string to a new file
Line 1,351 ⟶ 1,516:
NSLog(@"%@", aString);
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
Line 1,357 ⟶ 1,522:
For most uses we can use this function:
 
<langsyntaxhighlight lang="ocaml">let load_file f =
let ic = open_in f in
let n = in_channel_length ic in
Line 1,363 ⟶ 1,528:
really_input ic s 0 n;
close_in ic;
(s)</langsyntaxhighlight>
 
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>:
<syntaxhighlight lang ="ocaml"> (Bytes.unsafe_to_string s)</langsyntaxhighlight>
 
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,372 ⟶ 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:
 
<langsyntaxhighlight lang="ocaml">type big_string =
(char, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t</langsyntaxhighlight>
 
The function below returns the contents of a file with this type <code>big_string</code>, and it does so with "memory-mapping":
 
<langsyntaxhighlight lang="ocaml">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
Line 1,385 ⟶ 1,550:
Bigarray.char Bigarray.c_layout shared len in
Unix.close fd;
(bstr)</langsyntaxhighlight>
 
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):
 
<langsyntaxhighlight lang="ocaml">let () =
let bstr = load_big_file Sys.argv.(1) in
let len = Bigarray.Array1.dim bstr in
Line 1,395 ⟶ 1,560:
let c = bstr.{i} in
print_char c
done</langsyntaxhighlight>
 
=={{header|OlOdin}}==
<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}}==
===version 1===
<langsyntaxhighlight ooRexxlang="oorexx">file = 'c:\test.txt'
myStream = .stream~new(file)
myString = myStream~charIn(,myStream~chars)</langsyntaxhighlight>
 
Streams are opened on demand and closed when the script finishes.
It is possible if you wish to open and close the streams explicitly
 
<langsyntaxhighlight ooRexxlang="oorexx">file = 'c:\test.txt'
myStream = .stream~new(file)
if mystream~open('read') = 'READY:'
Line 1,421 ⟶ 1,597:
myString = myStream~charIn(,myStream~chars)
myStream~close
end</langsyntaxhighlight>
 
===version 2 EXECIO===
One can also use EXECIO as it is known from VM/CMS and MVS/TSO:
<langsyntaxhighlight lang="rexx">address hostemu 'execio * diskr "./st.in" (finis stem in.'
Say in.0 'lines in file st.in'
v=''
Line 1,433 ⟶ 1,609:
End
say 'v='v
::requires "hostemu" LIBRARY </langsyntaxhighlight>
{{out}}
<pre>E:\>rexx ref
Line 1,445 ⟶ 1,621:
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
</pre>
 
=={{header|OxygenBasic}}==
Two Formats:
<pre>
 
string s
 
'AS FUNCTION
 
s=GetFile "t.txt"
 
'AS PROCEDURE
 
Getfile "t.txt",s
 
</pre>
 
=={{header|Oz}}==
The interface for file operations is object-oriented.
<langsyntaxhighlight lang="oz">declare
FileHandle = {New Open.file init(name:"test.txt")}
FileContents = {FileHandle read(size:all list:$)}
in
{FileHandle close}
{System.printInfo FileContents}</langsyntaxhighlight>
<code>FileContents</code> is a list of bytes. The operation does not assume any particular encoding.
 
=={{header|Panda}}==
It returns a unicode string of type 'text'.
<syntaxhighlight lang ="panda">file:readme.txt .text</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
Line 1,482 ⟶ 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.
 
<langsyntaxhighlight lang="parigp">str = concat(apply(s->concat(s,"\n"), readstr("file.txt")))</langsyntaxhighlight>
 
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,493 ⟶ 1,653:
The modern recommended way, is using one of these CPAN modules:
 
* <langsyntaxhighlight lang="perl">use File::Slurper 'read_text';
my $text = read_text($filename, $data);</langsyntaxhighlight>
* <langsyntaxhighlight lang="perl">use Path::Tiny;
my $text = path($filename)->slurp_utf8;</langsyntaxhighlight>
* <langsyntaxhighlight lang="perl">use IO::All;
$text = io($filename)->utf8->all;</langsyntaxhighlight>
 
Traditional ways, without CPAN modules:
 
* <langsyntaxhighlight lang="perl">open my $fh, '<:encoding(UTF-8)', $filename or die "Could not open '$filename': $!";
my $text;
read $fh, $text, -s $filename;
close $fh;</langsyntaxhighlight>
*<langsyntaxhighlight lang="perl">my $text;
{
local $/ = undef;
Line 1,512 ⟶ 1,672:
$text = <$fh>;
close $fh;
}</langsyntaxhighlight>
* <langsyntaxhighlight lang="perl">my $text = do { local( @ARGV, $/ ) = ( $filename ); <> };</langsyntaxhighlight>
 
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).
<langsyntaxhighlight lang="perl">perl -n -0777 -e 'print "file len: ".length' stuff.txt</langsyntaxhighlight>
 
===Memory-mapping===
<langsyntaxhighlight Perllang="perl">use File::Map 'map_file';
map_file(my $str, "foo.txt");
print $str;</langsyntaxhighlight>
 
<langsyntaxhighlight Perllang="perl">use Sys::Mmap;
Sys::Mmap->new(my $str, 0, 'foo.txt')
or die "Cannot Sys::Mmap->new: $!";
print $str;</langsyntaxhighlight>
 
<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,532 ⟶ 1,692:
=={{header|Phix}}==
{{libheader|Phix/basics}}
<!--<langsyntaxhighlight Phixlang="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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,544 ⟶ 1,704:
=={{header|PHP}}==
Read as string
<syntaxhighlight lang ="php">file_get_contents($filename)</langsyntaxhighlight>
Read as array, one element per line
<syntaxhighlight lang ="php">file($filename)</langsyntaxhighlight>
 
=={{header|Picat}}==
The encoding is always UTF-8. Anything more than a small file will cause a buffer overflow.
 
{{works with|Picat}}
<syntaxhighlight lang="picat">
main(Args) =>
File = Args[1],
String = read_file_chars(File).
</syntaxhighlight>
 
=={{header|PicoLisp}}==
Using '[http://software-lab.de/doc/refT.html#till till]' is the shortest way:
<langsyntaxhighlight PicoLisplang="picolisp">(in "file" (till NIL T))</langsyntaxhighlight>
To read the file into a list of characters:
<langsyntaxhighlight PicoLisplang="picolisp">(in "file" (till NIL))</langsyntaxhighlight>
or, more explicit:
<langsyntaxhighlight PicoLisplang="picolisp">(in "file" (make (while (char) (link @))))</langsyntaxhighlight>
Encoding is always assumed to be UTF-8.
 
=={{header|Pike}}==
<langsyntaxhighlight lang="pike">string content=Stdio.File("foo.txt")->read();</langsyntaxhighlight>
would be the generic way of reading an entire file, but there is also a special function for it:
<langsyntaxhighlight lang="pike">string content=Stdio.read_file("foo.txt");</langsyntaxhighlight>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
get file (in) edit ((substr(s, i, 1) do i = 1 to 32767)) (a);
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
<syntaxhighlight lang ="powershell">Get-Content foo.txt</langsyntaxhighlight>
This will only detect Unicode correctly with a BOM in place (even for UTF-8). With explicit selection of encoding:
<langsyntaxhighlight lang="powershell">Get-Content foo.txt -Encoding UTF8</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="powershell">(Get-Content foo.txt) -join "`n"</langsyntaxhighlight>
 
=={{header|Prolog}}==
Read a text file. The third argument of read_file_to_string could be options.
 
{{works with|SWI Prolog}}
<syntaxhighlight lang="prolog">
:- initialization(main).
 
main :-
current_prolog_flag(argv, [File|_]),
read_file_to_string(File, String, []).
</syntaxhighlight>
 
=={{header|PureBasic}}==
A file can be read with any of the built in commands
<langsyntaxhighlight PureBasiclang="purebasic">Number.b = ReadByte(#File)
Length.i = ReadData(#File, *MemoryBuffer, LengthToRead)
Number.c = ReadCharacter(#File)
Line 1,585 ⟶ 1,767:
Number.q = ReadQuad(#File)
Text$ = ReadString(#File [, Flags])
Number.w = ReadWord(#File)</langsyntaxhighlight>
If the file is s pure text file (no CR/LF etc.), this will work and will read each line untill EOL is found.
<langsyntaxhighlight PureBasiclang="purebasic">If ReadFile(0, "RC.txt")
Variable$=ReadString(0)
CloseFile(0)
EndIf</langsyntaxhighlight>
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.
<langsyntaxhighlight PureBasiclang="purebasic">Title$="Select a file"
Pattern$="Text (.txt)|*.txt|All files (*.*)|*.*"
fileName$ = OpenFileRequester(Title$,"",Pattern$,0)
Line 1,605 ⟶ 1,787:
CloseFile(0)
EndIf
EndIf</langsyntaxhighlight>
 
=={{header|Python}}==
 
<syntaxhighlight lang ="python">open(filename).read()</langsyntaxhighlight>
 
This returns a byte string and does not assume any particular encoding.
Line 1,615 ⟶ 1,797:
In Python 3 strings are in unicode, you can specify encoding when reading:
 
<langsyntaxhighlight lang="python">open(filename, encoding='utf-8').read()</langsyntaxhighlight>
 
Python docs recommend dealing with files using the with statement:
 
<langsyntaxhighlight lang="python">with open(filename) as f:
data = f.read()</langsyntaxhighlight>
 
Starting in Python 3.4, we can use <code>pathlib</code> to reduce boilerplate:
 
<langsyntaxhighlight lang="python">from pathlib import Path
 
any_string = Path(filename).read_text(encoding='utf-8')
any_binary_data = Path(filename).read_bytes()</langsyntaxhighlight>
 
=={{header|Quackery}}==
Line 1,633 ⟶ 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).
 
<langsyntaxhighlight Quackerylang="quackery">$ "myfile.txt" sharefile</langsyntaxhighlight>
 
=={{header|Q}}==
 
<langsyntaxhighlight Qlang="q">q)file:read0`:file.txt
"First line of file"
"Second line of file"
""</langsyntaxhighlight>
 
=={{header|R}}==
 
<langsyntaxhighlight lang="r">fname <- "notes.txt"
contents <- readChar(fname, file.info(fname)$size)</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">(file->string "foo.txt")</langsyntaxhighlight>
 
=={{header|Raku}}==
Line 1,655 ⟶ 1,837:
 
{{works with|Rakudo|2010.07}}
<syntaxhighlight lang="raku" perl6line>my $string = slurp 'sample.txt';</langsyntaxhighlight>
 
The default encoding is UTF-8. The <tt>:enc</tt> adverb can be used to specify a different one:
 
<syntaxhighlight lang="raku" perl6line>my $string = slurp 'sample.txt', :enc<UTF-16>;</langsyntaxhighlight>
 
<tt>IO::Path</tt> objects also provide <tt>slurp</tt> as a method:
<syntaxhighlight lang="raku" perl6line>my $string = 'sample.txt'.IO.slurp;</langsyntaxhighlight>
 
=={{header|Raven}}==
<langsyntaxhighlight Ravenlang="raven">'myfile.txt' read as $content_as_string</langsyntaxhighlight>
or
<langsyntaxhighlight Ravenlang="raven">'file://r:/home/me/myfile.txt' open as $handle
$handle read as $content_as_string
$handle close</langsyntaxhighlight>
 
=={{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]
<langsyntaxhighlight lang="realbasic">
Function readFile(theFile As FolderItem, txtEncode As TextEncoding = Nil) As String
Dim fileContents As String
Line 1,685 ⟶ 1,867:
MsgBox("File Not Found.")
End Function
</syntaxhighlight>
</lang>
 
=={{header|REBOL}}==
<langsyntaxhighlight lang="rebol">read %my-file ; read as text
read/binary %my-file ; preserve contents exactly</langsyntaxhighlight>
 
=={{header|Retro}}==
<syntaxhighlight lang="retro">
<lang Retro>
here 'input.txt file:slurp</langsyntaxhighlight>
 
=={{header|REXX}}==
===using LINEIN===
<langsyntaxhighlight 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.*/
if iFID=='' then iFID= 'a_file' /*Not specified? Then use the default.*/
Line 1,703 ⟶ 1,885:
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. */</langsyntaxhighlight>
 
===using CHARIN===
Note that CRLF are in the resulting string.
<syntaxhighlight lang="text">/*REXX program reads a file and stores it as a continuous character str.*/
Parse Version v
iFID = 'st.in' /*name of the input file. */
Line 1,723 ⟶ 1,905:
say 'v='v
say 'length(v)='length(v)
</langsyntaxhighlight>
{{out}}
<pre>E:\>rexx refc
Line 1,733 ⟶ 1,915:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Read the file
cStr = read("myfile.txt")
# print the file content
See cStr
</syntaxhighlight>
</lang>
 
Also in one line we can read and print the file content.
 
<langsyntaxhighlight lang="ring">
cStr = read("myfile.txt") See cStr
</syntaxhighlight>
</lang>
 
We can avoid the string, but it's required in the task.
 
<langsyntaxhighlight lang="ring">
See read("myfile.txt")
</syntaxhighlight>
</lang>
 
=={{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".
 
<langsyntaxhighlight lang="ruby"># Read entire text file.
str = IO.read "foobar.txt"
 
# It can also read a subprocess.
str = IO.read "| grep ftp /etc/services"</langsyntaxhighlight>
 
''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.
 
<langsyntaxhighlight lang="ruby">path = "|strange-name.txt"
str = File.open(path) {|f| f.read}</langsyntaxhighlight>
 
To read a binary file, open it in binary mode.
 
<langsyntaxhighlight lang="ruby"># Read entire binary file.
str = File.open(path, "rb") {|f| f.read}</langsyntaxhighlight>
 
Ruby 1.9 can read text files in different encodings.
 
{{works with|Ruby|1.9}}
<langsyntaxhighlight lang="ruby"># 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}</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight Runbasiclang="runbasic">open DefaultDir$ + "/public/test.txt" for binary as #f
fileLen = LOF(#f)
a$ = input$(#f, fileLen)
print a$
close #f</langsyntaxhighlight>
 
=={{header|Rust}}==
 
<langsyntaxhighlight lang="rust">use std::fs::File;
use std::io::Read;
 
Line 1,803 ⟶ 1,985:
let filestr = String::from_utf8(contents).unwrap();
println!("{}", filestr);
}</langsyntaxhighlight>
 
=={{header|Scala}}==
{{libheader|Scala}}
<langsyntaxhighlight lang="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()
}
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
Uses SRFI-13:
<langsyntaxhighlight lang="scheme">(with-input-from-file "foo.txt"
(lambda ()
(reverse-list->string
Line 1,823 ⟶ 2,005:
(if (eof-object? char)
result
(loop (read-char) (cons char result)))))))</langsyntaxhighlight>
 
Works with Chicken Scheme:
<langsyntaxhighlight lang="scheme">(with-input-from-file "foo.txt" read-string)</langsyntaxhighlight>
 
In GNU Guile, with decoding into Unicode code points:
<langsyntaxhighlight lang="scheme">(use-modules (ice-9 textual-ports))
(call-with-input-file "foo.txt" get-string-all)</langsyntaxhighlight>
 
=={{header|Seed7}}==
Line 1,836 ⟶ 2,018:
defines the function [http://seed7.sourceforge.net/libraries/getf.htm#getf%28in_string%29 getf],
which reads a whole file into a string:
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "getf.s7i";
 
Line 1,844 ⟶ 2,026:
begin
fileContent := getf("text.txt");
end func;</langsyntaxhighlight>
 
=={{header|SenseTalk}}==
<langsyntaxhighlight lang="sensetalk">Put file "~/Documents/myFile.txt" into TestFile
put testFile</langsyntaxhighlight>
 
=={{header|Sidef}}==
Reading an entire file as a string, can be achieved with the '''FileHandle.slurp()''' method, as illustrated bellow:
<langsyntaxhighlight lang="ruby">var file = File.new(__FILE__);
var content = file.open_r.slurp;
print content;</langsyntaxhighlight>
 
Starting with version 2.30, ''File.read()'' can do the same:
<langsyntaxhighlight lang="ruby">var file = File(__FILE__)
var content = file.read(:utf8)
print content</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
{{works with|Pharo}}
<langsyntaxhighlight lang="smalltalk">(StandardFileStream oldFileNamed: 'foo.txt') contents</langsyntaxhighlight>
{{works with|Smalltalk/X}}
<syntaxhighlight lang ="smalltalk">'foo.txt' asFilename contentsAsString</langsyntaxhighlight>
 
=={{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.
 
<langsyntaxhighlight SNOBOL4lang="snobol4"> input(.inbin,21,"filename.txt [-r524288]") :f(end)
rdlp buf = inbin :s(rdlp)
*
* now process the 'buf' containing the file
*
end</langsyntaxhighlight>
 
=={{header|Sparkling}}==
<langsyntaxhighlight lang="sparkling">let contents = readfile("foo.txt");</langsyntaxhighlight>
 
=={{header|SPL}}==
<langsyntaxhighlight lang="spl">text = #.readtext("filename.txt")</langsyntaxhighlight>
 
=={{header|Standard ML}}==
<syntaxhighlight lang="sml">
<lang sml>fun readFile path =
(* string -> string *)
fun readFile path =
(fn strm =>
TextIO.inputAll strm before TextIO.closeIn strm) (TextIO.openIn path)</langsyntaxhighlight>
</syntaxhighlight>
 
=={{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.
 
<langsyntaxhighlight lang="stata">mata
f = fopen("somedata.txt", "r")
fseek(f, 0, 1)
Line 1,898 ⟶ 2,083:
s = fread(f, n)
fclose(f)
end</langsyntaxhighlight>
 
=={{header|Swift}}==
{{works with|Swift|1}}
<lang Swift>import Foundation
 
<syntaxhighlight lang="swift">import Foundation
 
let path = "~/input.txt".stringByExpandingTildeInPath
if let string = String(contentsOfFile: path, encoding: NSUTF8StringEncoding) {
println(string) // print contents of file
}</langsyntaxhighlight>
 
{{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}}==
This reads the data in as text, applying the default encoding translations.
<langsyntaxhighlight lang="tcl">set f [open $filename]
set data [read $f]
close $f</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="tcl">set f [open $filename "rb"]
set data [read $f]
close $f</langsyntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
ERROR/STOP OPEN ("rosetta.txt",READ,-std-)
var=FILE ("rosetta.txt")
</syntaxhighlight>
</lang>
 
=={{header|TXR}}==
 
<langsyntaxhighlight lang="txr">@(next "foo.txt")
@(freeform)
@LINE
</syntaxhighlight>
</lang>
 
The freeform directive in TXR causes the remaining lines of the text stream
Line 1,945 ⟶ 2,147:
we tell 'printf' to add an extra newline.
 
<langsyntaxhighlight lang="sh">f=`cat foo.txt` # f will contain the entire contents of the file
printf '%s\n' "$f"</langsyntaxhighlight>
 
<langsyntaxhighlight lang="bash">f=$(cat foo.txt)
printf '%s\n' "$f"</langsyntaxhighlight>
 
Some shells provide a shortcut to read a file without starting a 'cat' process.
Line 1,956 ⟶ 2,158:
{{works with|pdksh}}
 
<langsyntaxhighlight lang="bash">f=$(<foo.txt)
echo -E "$f"</langsyntaxhighlight>
 
{{works with|zsh}}
<langsyntaxhighlight lang="bash">file=$(<foo.txt)
print $file</langsyntaxhighlight>
alternatively
<langsyntaxhighlight lang="bash">zmodload zsh/mapfile
print $mapfile[foo.txt]</langsyntaxhighlight>
 
=={{header|Ursa}}==
<langsyntaxhighlight lang="ursa">decl string contents
decl file f
f.open "filename.txt"
set contents (f.readall)</langsyntaxhighlight>
 
=={{header|Vala}}==
<langsyntaxhighlight lang="vala">
string file_contents;
FileUtils.get_contents("foo.txt", out file_contents);
</syntaxhighlight>
</lang>
 
=={{header|VBScript}}==
Read text file with default encoding into variable and display
<langsyntaxhighlight lang="vb">dim s
s = createobject("scripting.filesystemobject").opentextfile("slurp.vbs",1).readall
wscript.echo s</langsyntaxhighlight>
 
Read text file with UTF-16 encoding into memory and display
<langsyntaxhighlight lang="vb">wscript.echo createobject("scripting.filesystemobject").opentextfile("utf16encoded.txt",1,-1).readall</langsyntaxhighlight>
 
=={{header|Vedit macro language}}==
Line 1,994 ⟶ 2,196:
 
Read file into edit buffer. The buffer is allocated automatically:
<langsyntaxhighlight lang="vedit">File_Open("example.txt")</langsyntaxhighlight>
 
Read file into text register 10:
<langsyntaxhighlight lang="vedit">Reg_Load(10, "example.txt")</langsyntaxhighlight>
 
=={{header|Visual Basic}}==
{{works with|Visual Basic|5}}
{{works with|Visual Basic|6}}
<langsyntaxhighlight lang="vb">Declare Function MultiByteToWideChar Lib "kernel32.dll" ( _
ByVal CodePage As Long, _
ByVal dwFlags As Long, _
Line 2,038 ⟶ 2,240:
Close #fn
Debug.Print s
End Sub</langsyntaxhighlight>
 
=={{header|Visual Basic .NET}}==
<langsyntaxhighlight lang="vbnet">Imports System.IO
 
Public Class Form1
Line 2,056 ⟶ 2,258:
End Sub
 
End Class</langsyntaxhighlight>
 
=={{header|Wart}}==
<langsyntaxhighlight lang="wart">with infile "x"
with outstring
whilet line (read_line)
prn line</langsyntaxhighlight>
 
=={{header|Wren}}==
Line 2,070 ⟶ 2,272:
For the following script, a file called "input.txt" has been created which contains the string "abcdefghijklmnopqrstuvwxyz".
<langsyntaxhighlight ecmascriptlang="wren">import "io" for File
 
System.print(File.read("input.txt"))</langsyntaxhighlight>
 
{{out}}
Line 2,083 ⟶ 2,285:
The command line is: readfile <readfile.xpl
 
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated string convention
int I;
Line 2,095 ⟶ 2,297:
SetHp(Str+I+1); \set heap pointer beyond Str (not really needed here)
Text(0, Str); \show file as a string
]</langsyntaxhighlight>
 
{{Out}}
Line 2,115 ⟶ 2,317:
 
=={{header|Xtend}}==
<langsyntaxhighlight lang="java">
package com.rosetta.example
 
Line 2,126 ⟶ 2,328:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Yorick}}==
Line 2,132 ⟶ 2,334:
Each array element is one line.
Each line's trailing newline is removed.
<langsyntaxhighlight lang="yorick">lines = rdfile("foo.txt");</langsyntaxhighlight>
This loads foo.txt into ''content'' as a single scalar string, without losing newlines.
<langsyntaxhighlight lang="yorick">f = open("foo.txt", "rb");
raw = array(char, sizeof(f));
_read, f, 0, raw;
close, f;
content = strchar(raw);</langsyntaxhighlight>
 
=={{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}}==
 
<langsyntaxhighlight lang="zkl">data := File("foo.txt","r").read()</langsyntaxhighlight>
The file parameters are the same as C's
23

edits