View Category

Read the contents of a file into a string

ruby
file = File.new("Solution108.rb")
whole_file = file.read
java
String text = FileUtils.readFileToString(new File("Solution109.java"), "UTF-8");
RandomAccessFile raf = null; byte[] buffer; String text = null;

try
{
raf = new RandomAccessFile("Solution399.java", "r");
buffer = new byte[(int)raf.length()]; raf.read(buffer);
text = new String(buffer);
}
perl
@file = read()
open(my $fh, '<', $path) or die "can't open $path: $!";
$string = do { local $/; <$fh> };
close $fh;
groovy
contents = file.text
scala
val text = FileUtils.readFileToString(new File("Solution467.scala"))
val text = Source.fromFile("Solution1256.scala").mkString("")
python
contents = open('myFile.txt', 'rt').read()
cpp
IO::FileStream^ file; String^ buffer;

try
{
file = gcnew IO::FileStream("test.txt", IO::FileMode::Open);
buffer = gcnew String((gcnew IO::BinaryReader(file))->ReadChars(file->Length));
}
IO::StreamReader^ stream; String^ buffer;

try
{
stream = gcnew IO::StreamReader("test.txt");
buffer = stream->ReadToEnd();
}
String^ buffer = IO::File::ReadAllText("test.txt");
fsharp
let file = new FileStream("test.txt", FileMode.Open)
let buffer = new String((new BinaryReader(file)).ReadChars(Convert.ToInt32(file.Length)))
let stream = new StreamReader("test.txt")
let buffer = stream.ReadToEnd()
let buffer = File.ReadAllText("test.txt")
erlang
Text = readfile("Solution607.erl"),
Text = readfile("Solution608.erl"),
ocaml
let read_file f =
let ic = open_in f in
let n = in_channel_length ic in
let s = String.create n in
really_input ic s 0 n;
close_in ic;
(s)

let file_contents = read_file "file.txt"
csharp
string contents = System.IO.File.ReadAllText("filename.txt");
php
$file_contents = file_get_contents("file.txt");
haskell
readFile "c:/tmp/myFile.txt"
clojure
(slurp "/tmp/foobar")
fantom
contents := File(`file.text`).readAllStr

Process a file one line at a time

Open the source file to your solution and print each line in the file, prefixed by the line number, like:
1> First line of file
2> Second line of file
3> Third line of file
ruby
File.open("Solution103.rb").each_with_index { |line, count|
puts "#{count} > #{line}
}
java
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("Solution104.java"));
String line = null;
int lineNumber = 1;
while ((line=br.readLine())!=null) {
System.out.println(lineNumber + "> " + line);
lineNumber++;
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (br!=null) {
try {
br.close();
} catch (Exception e) {
// ok
}
}
}
LineNumberReader lnr = null; PrintWriter pw = null; String line;

try
{
lnr = new LineNumberReader(new FileReader("Solution400.java"));
pw = new PrintWriter(System.out);
while ((line = lnr.readLine()) != null) pw.printf("%d> %s\n", lnr.getLineNumber(), line);
}
perl
open(my $fh, '<', $path) or die "can't open $path: $!";
$c = 1;
print $c++ . "> $_" for (<$fh>);
close $fh;
open my $fh, '<', $path or die "Can't open $path: $!";
while (<$fh>) {
print "$.> $_";
}
groovy
int count = 0
file.eachLine { line ->
println "${++count} > $line"
}
file.eachLine { line, count ->
println "${++count} > $line"
}
scala
val source = Source.fromFile(new File("Solution468.scala")).getLines
var n = 1 ; while (source.hasNext) { printf("%d> %s", n, source.next) ; n += 1 }
val source = Source.fromFile(new File("Solution469.scala")).getLines
for ((line, n) <- source zipWithIndex) { printf("%d> %s", (n + 1), line) }
python
for no, line in enumerate(open(__file__)):
print "{0}> {1}".format(no+1, line.rstrip())
cpp
IO::StreamReader^ stream; String^ ln; int i = 0;

try
{
stream = gcnew IO::StreamReader("test.txt");
while ((ln = stream->ReadLine())) Console::WriteLine("{0}> {1}", ++i, ln);
}
int i = 0;
for each(String^ line in IO::File::ReadAllLines("test.txt")) Console::WriteLine("{0}> {1}", ++i, line);
fsharp
let stream = new StreamReader("test.txt")
let mutable i = 1
let mutable line = stream.ReadLine()
while (line <> null) do printfn "%d> %s" i line ; line <- stream.ReadLine() ; i <- i + 1 done
stream.Close()
let proc_a_line (filename : string) proc =
let stream = new StreamReader(filename)
let rec proc_a_line' count line =
match line with
| null -> stream.Close()
| _ -> proc count line ; proc_a_line' (count + 1) (stream.ReadLine())
proc_a_line' 1 (stream.ReadLine())

// ------

let _ = proc_a_line "test.txt" (fun i line -> printfn "%d> %s" i line)
let reader(filename : string) = seq {
use sr = new StreamReader(filename)
while not sr.EndOfStream do
let line = sr.ReadLine()
yield line
done
}

// ------

reader("test.txt") |> Seq.iteri (fun i line -> printfn "%d> %s" (i + 1) line)
File.ReadAllLines("test.txt") |> Array.iteri (fun i line -> printfn "%d> %s" (i + 1) line)
// Unlike ReadAllLines, ReadLines (new in .NET 4) only reads the file
// one line at a time, rather than reading the entire file into an array first.

open System.IO
File.ReadLines("test.txt") |> Seq.iteri (fun i line -> printfn "%d> %s" (i + 1) line)
erlang
Reader = fun (IODevice) -> io:get_line(IODevice, "") end,
Worker = fun (Line, N) -> io:format("~B> ~s", [N, Line]), N + 1 end,

while_not_eof("Solution609.erl", Reader, Worker, 1).
Reader = fun (Filename) -> {ok, Contents} = file:read_file(Filename), Contents end,
Transformer = fun (Line, N) -> string:concat(string:concat(integer_to_list(N), "> "), Line) end,
Printer = fun (Line) -> io:format("~s~n", [Line]) end,

Lines = string:tokens(binary_to_list(Reader("Solution610.erl")), "\n"),
NewLines = lists:zipwith(Transformer, Lines, lists:seq(1, length(Lines))),
lists:foreach(Printer, NewLines).
ocaml
let () =
let ic = open_in Sys.argv.(1) in
let i = ref 1 in
try
while true do
Printf.printf "%d> %s\n" !i (input_line ic);
incr i
done
with End_of_file ->
close_in ic
let input_line_opt ic =
try Some (input_line ic)
with End_of_file -> None

let () =
let ic = open_in Sys.argv.(1) in
let rec aux i =
match input_line_opt ic with
| Some line ->
Printf.printf "%d> %s\n" i line;
aux (succ i)
| None ->
close_in ic
in
aux 1
csharp
int counter = 0;

// If the file is large, you would want to buffer this instead of reading everything at once
foreach (string line in System.IO.File.ReadAllLines("filename.txt"))
{
Console.WriteLine("{0}> {1}", ++counter, line);
}
php
$lines = file('file.txt');
foreach ($lines as $lnum => $line) {
echo $line_num."> ".$line; // you may want to add a <br />\n
}
<?php
$lines = new SplFileObject('file.txt');
foreach ($lines as $line) {
echo $line;
}
?>
haskell
import Data.List

prefixWithNumber str n = show n ++ "> " ++ str

numberStrings (x:xs) n = prefixWithNumber x n : (numberStrings xs (n+1))
numberStrings [] n = []

main = do
str <- readFile "prefix.hs"
putStrLn (intercalate "\n" (numberStrings (lines str) 1))
prefix n str = show n ++ "> " ++ str

main = readFile "prefix.hs" >>=
putStr . unlines . zipWith prefix [1..] . lines
clojure
(defn read-line-by-line [fn]
(reduce str (map (partial format "%d> %s\n")
(iterate inc 1)
(read-lines fn))))
fantom
File(`input.text`).readAllLines.each |Str s, Int i| { echo("${i+1}> $s") }

Write a string to a file

ruby
File.new("a_file", "w") << "some text"
IO.write("file.txt", "some text that overwrites")
java
FileWriter fw = null;

try
{
fw = new FileWriter("test.txt");
fw.write("This line overwites file contents!");
}
PrintWriter pw = null;

try
{
pw = new PrintWriter(new BufferedWriter(new FileWriter("test.txt")));
pw.print("This line overwites file contents!");
}
perl
open(my $fh, '>', $path) or die "can't open $path: $!";
print $fh "This line overwites file contents!";
close $fh;
groovy
file.delete()
file << 'some text'
file.text = 'some text'
scala
FileUtils.writeStringToFile(new File("test.txt"), "This line overwites file contents!")
val fw = new FileWriter("test.txt") ; fw.write("This line overwites file contents!") ; fw.close()
python
open('test.txt', 'wt').write('Hello World!')
cpp
IO::StreamWriter^ stream;

try
{
stream = gcnew IO::StreamWriter("test.txt", false);
stream->WriteLine("This line overwites file contents!");
}
fsharp
let stream = new StreamWriter("test.txt", false)
stream.WriteLine("This line overwrites file contents!")
erlang
Line = "This line overwites file contents!\n",
{ok, IODevice} = file:open("test.txt", [write]), file:write(IODevice, Line), file:close(IODevice).
ocaml
try
let cout = open_out filename in
let co = Format.formatter_of_out_channel cout in
Format.fprintf co "%s\n" text_to_write;
close_out cout
with Sys_error _ as e ->
Format.printf "Cannot open file \"%s\": %s\n" filename (Printexc.to_string e)
csharp
System.IO.File.WriteAllText("filename.txt", "Some text to write to the file");
php
/****
* For some (security)reason I couldn't
* submit this without adding a space to
* the functionnames. Please remove it :)
****/

if ($fh = f open("file.txt", 'w')) {
f write($fh, "Some text\n");
f close($fh);
}
<?php
file_put_contents('file.txt', 'a string');
?>
haskell
writeFile "filename" "stringe"
clojure
(with-out-writer "output.txt" (println "Hello file!"))
fantom
File(`out.txt`).out.writeChars("some text").flush

Append to a file

ruby
file = File.new('/tmp/test.txt', 'a+') ; file.puts 'This line appended to file!!' ; file.close()
java
FileWriter fw = null;

try
{
fw = new FileWriter("test.txt", true);
fw.write("This line appended to file!");
}
PrintWriter pw = null;

try
{
pw = new PrintWriter(new BufferedWriter(new FileWriter("test.txt", true)));
pw.print("This line appended to file!");
}
perl
open(my $fh, '>>', $path) or die "can't open $path: $!";
print $fh "This line is appended to the file!";
close $fh;
groovy
file << 'some text'
scala
val fw = new FileWriter("test.txt", true) ; fw.write("This line appended to file!") ; fw.close()
python
open('test.txt', 'at').write('Hello World!\n')
cpp
IO::StreamWriter^ stream;

try
{
stream = gcnew IO::StreamWriter("test.txt", true);
stream->WriteLine("This line appended to file!");
}
fsharp
let stream = new StreamWriter("test.txt", true)
stream.WriteLine("This line appended to file!")
erlang
Line = "This line appended to file!\n",
{ok, IODevice} = file:open("test.txt", [append]), file:write(IODevice, Line), file:close(IODevice).
ocaml
let () =
let oc =
open_out_gen
[Open_wronly; Open_creat; Open_append; Open_text] 0o666 "test.txt" in
output_string oc "This line appended to file!\n";
close_out oc
csharp
System.IO.File.AppendAllText("filename.txt", "Some text to append to the file");
php
<?php
if ($fh = fopen("file.txt", 'a')) { // a == append
fwrite($fh, "Append some text\n");
fclose($fh);
}
?>
<?php
file_put_contents('file.txt', 'a string to append', FILE_APPEND);
?>
haskell
appendfile "filename" "string"
clojure
(with-out-append-writer "output.txt" (println "This is appended to the file"))
fantom
File(`out.txt`).out(true).writeChars("some text").flush

Process each file in a directory

ruby
directory = '/tmp' ; Dir.foreach(directory) {|file| puts "#{file}"}
java
for (File file : (new File("c:\\")).listFiles()) process(file);
perl
use File::Glob;

for (<*>) {
process_file($_) if (-f);
}
groovy
dir.eachFile{ f -> process(f) }
scala
for (file <- new File("c:\\").listFiles) { processFile(file) }
python
import os
results = (process(f) for f in os.listdir(".") if os.path.isfile(f))
cpp
for each(String^ filename in IO::Directory::GetFiles(dirname)) process(filename);
fsharp
let dirname = "c:\\"

let processFile filename = printfn "%s" filename
for filename in Directory.GetFiles(dirname) do processFile filename done
let dirname = "c:\\"

Directory.GetFiles(dirname) |> Array.iter (fun filename -> printfn "%s" filename)
erlang
% File basenames only - many tasks require absolute paths to work
lists:foreach(fun (FileOrDirPath) -> Worker(FileOrDirPath) end, file:list_dir(Directory)).
% Absolute paths provided - will accomodate most tasks
lists:foreach(fun (FileOrDirPath) -> Worker(FileOrDirPath) end, list_dir_path(Directory)).
ocaml
let process dir file =
if not (Sys.is_directory (Filename.concat dir file))
then print_endline file

let () =
let dir = "." in
let files = Sys.readdir dir in
Array.iter (process dir) files
csharp
foreach (string filename in System.IO.Directory.GetFiles(directory)) ProcessFile(filename);
php
if ($dh = opendir($dir)) { // if we have access
while (($file = readdir($dh)) !== false) { // as long as there is a file
echo "name: $file\n"; // echo its name
}
closedir($dh); // close the dir
}
haskell
import System.Directory
import Control.Monad

process filename = putStrLn filename

main = getDirectoryContents "." >>=
filterM doesFileExist >>=
mapM_ process
clojure
; (defn process-file [f] "process one file" body...)
(map process-file (.listFiles (File. ".")))
fantom
File(`./`).list.each { process(it) }

Process each file in a directory recursively

ruby
def procdir(dirname)
Dir.foreach(dirname) do |dir|
dirpath = dirname + '/' + dir
if File.directory?(dirpath) then
if dir != '.' && dir != '..' then
puts "DIRECTORY: #{dirpath}" ; procdir(dirpath)
end
else
puts "FILE: #{dirpath}"
end
end
end

# ------

procdir('/tmp')
java
processDirectory(new File("c:\\"));
perl
use File::Glob;

process_directory(".");

sub process_directory {
my $dir = shift;
for my $file (<$dir/*>) {
next unless (-r $file);
if (-f $file) {
process_file($file);
} elsif (-d $file) {
process_directory($file);
}
}
}
use File::Find ();

# Traverse desired filesystems
sub process_directory {
my $directory = shift;
File::Find::find({wanted => \&wanted}, $directory);
}

sub wanted {
process_file( $File::Find::name );
}
groovy
dir.eachFileRecurse{ f -> process(f) }
scala
processDirectory(new File("c:\\"))
python
import os
results = (process(os.path.join(p, n)) for p,d,l in os.walk(".") for n in l)
cpp
void processFile(String^ filename) { Console::WriteLine("{0}", filename); }

void processDirectory(String^ dirname)
{
for each(String^ filename in IO::Directory::GetFiles(dirname)) processFile(filename);
for each(String^ subdirname in IO::Directory::GetDirectories(dirname)) processDirectory(subdirname);
}

int main()
{
processDirectory("c:\\");
}
fsharp
let processDirectory dirname proc =
let rec processDirectory' dirname' =
Directory.GetFiles(dirname') |> Array.iter proc
Directory.GetDirectories(dirname') |> Array.iter processDirectory'
processDirectory' dirname

// ------

let dirname = "c:\\"

processDirectory dirname (fun filename -> printfn "%s" filename)
erlang
filelib:fold_files(Directory, ".*", true, fun (FileOrDirPath, Acc) -> Worker(FileOrDirPath), Acc end, []).
process_dir(Directory, Worker).
ocaml
let rec recurse_dir dir f =
let filenames = Sys.readdir dir in
Array.iter (fun name ->
let fullname = Filename.concat dir name in
if Sys.is_directory fullname then
recurse_dir fullname f
else
f fullname
) filenames
;;
recurse_dir (Sys.getenv "HOME") print_endline ;;
php

if ($dir_handle = opendir($dir))
list_dir($dir_handle);

function list_dir($dh) {
// as long as we can read the dir
while (($file = readdir($dh)) !== false) {
// if it's a dir and it's not the current dir nor the above dir
if (is_dir($file) && $file != '.' && $file !='..') {
// open the dir, print it's name and all files inside
$handle = opendir($file);
echo $file."\n";
list_dir($handle);
// if it's a simple file
} else if ($file != '.' && $file !='..') {
// type it's name
echo $file."\n";
}
}
closedir($dir_handle); // close the dirs
}
haskell
import System.Directory (doesFileExist, getDirectoryContents)
import System.FilePath ((</>))

process :: FilePath -> IO ()
process filename = putStrLn filename

mapDir :: (FilePath -> IO ()) -> FilePath -> IO ()
mapDir proc fp = do
isFile <- doesFileExist fp -- is a file of fp
if isFile then proc fp -- process the file
else getDirectoryContents fp >>=
mapM_ (mapDir proc . (fp </>)) . filter (`notElem` [".", ".."])

main = mapDir process "."
clojure
; (defn process-file [f] "process one file" body...)
(map process-file (file-seq (File. ".")))
fantom
File(`./`).walk { process(it) }