Head And Tail
November 13, 2015
Today’s exercise is a simple file-handling task for beginning programmers: take the name of a text file as input and write as output the first and last lines of the file.
Your task is to write the file-handling program described above. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Scala with iterator
Haskell:
FSharp :
Haskell:
head -1 $1; tail -1 $1
I memory-mapped the file as a byte array. I wanted to learn about that.
A source says it is guaranteed that an ASCII byte cannot occur in the middle of a UTF-8 character; other assumptions about what line-end characters occur where in the file remain because I couldn’t be bothered.
Testing with the source code file itself:
// C#:
string[] lines = File.ReadAllLines(@”file.txt”);
if (lines.Length != 0)
{
MessageBox.Show(lines[0] + “\n” + lines[lines.Length – 1]);
}
Here’s a C++ solution that just uses some basic Unix system functions – sbrk and brk for memory allocation, read and write for I/0. Probably should check return codes & allow for partial writes. Could be more intelligent about copying data from the input buffer too.
;; A Simple Clisp solution
(defun head-tail(name)
(let (last)
(with-open-file (file name)
(print (read-line file))
(loop for x = (read-line file nil) while x do
(setf last x))
(print last))))
Using the Reverse_file_buf from my solution to the 17 November 2015 exercise…
It’s pretty fast even on large files (despite the inefficiencies of Reverse_file_buf) because it jumps straight to the end to find the last line.
Some Racket Scheme solutions .