View Category

Read the contents of a file into a string

ruby
file = File.new("Solution108.rb")
whole_file = file.read
csharp
string contents = System.IO.File.ReadAllText("filename.txt");
fantom
contents := File(`file.text`).readAllStr
clojure
(slurp "/tmp/foobar")

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}
}
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);
}
fantom
File(`input.text`).readAllLines.each |Str s, Int i| { echo("${i+1}> $s") }
clojure
(defn read-line-by-line [fn]
(reduce str (map (partial format "%d> %s\n")
(iterate inc 1)
(read-lines fn))))

Write a string to a file

ruby
File.new("a_file", "w") << "some text"
csharp
System.IO.File.WriteAllText("filename.txt", "Some text to write to the file");
fantom
File(`out.txt`).out.writeChars("some text").flush
clojure
(with-out-writer "output.txt" (println "Hello file!"))

Append to a file

ruby
file = File.new('/tmp/test.txt', 'a+') ; file.puts 'This line appended to file!!' ; file.close()
csharp
System.IO.File.AppendAllText("filename.txt", "Some text to append to the file");
fantom
File(`out.txt`).out(true).writeChars("some text").flush
clojure
(with-out-append-writer "output.txt" (println "This is appended to the file"))

Process each file in a directory

ruby
directory = '/tmp' ; Dir.foreach(directory) {|file| puts "#{file}"}
csharp
foreach (string filename in System.IO.Directory.GetFiles(directory)) ProcessFile(filename);
fantom
File(`./`).list.each { process(it) }
clojure
; (defn process-file [f] "process one file" body...)
(map process-file (.listFiles (File. ".")))

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')
fantom
File(`./`).walk { process(it) }
clojure
; (defn process-file [f] "process one file" body...)
(map process-file (file-seq (File. ".")))