View Category

Read the contents of a file into a string

python
contents = open('myFile.txt', 'rt').read()
clojure
(slurp "/tmp/foobar")
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");

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
python
for no, line in enumerate(open(__file__)):
print "{0}> {1}".format(no+1, line.rstrip())
clojure
(defn read-line-by-line [fn]
(reduce str (map (partial format "%d> %s\n")
(iterate inc 1)
(read-lines fn))))
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);

Write a string to a file

python
open('test.txt', 'wt').write('Hello World!')
clojure
(with-out-writer "output.txt" (println "Hello file!"))
cpp
IO::StreamWriter^ stream;

try
{
stream = gcnew IO::StreamWriter("test.txt", false);
stream->WriteLine("This line overwites file contents!");
}

Append to a file

python
open('test.txt', 'at').write('Hello World!\n')
clojure
(with-out-append-writer "output.txt" (println "This is appended to the file"))
cpp
IO::StreamWriter^ stream;

try
{
stream = gcnew IO::StreamWriter("test.txt", true);
stream->WriteLine("This line appended to file!");
}

Process each file in a directory

python
import os
results = (process(f) for f in os.listdir(".") if os.path.isfile(f))
clojure
; (defn process-file [f] "process one file" body...)
(map process-file (.listFiles (File. ".")))
cpp
for each(String^ filename in IO::Directory::GetFiles(dirname)) process(filename);

Process each file in a directory recursively

python
import os
results = (process(os.path.join(p, n)) for p,d,l in os.walk(".") for n in l)
clojure
; (defn process-file [f] "process one file" body...)
(map process-file (file-seq (File. ".")))
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:\\");
}