Cat

June 8, 2012

One of the on-going themes here at Programming Praxis involves the re-implementation of the text utilities from Unix V7. Today we look at the cat command:

NAME

cat – catenate and print

SYNOPSIS

cat [ -u ] file …

DESCRIPTION

Cat reads each file in sequence and writes it on the standard output. Thus

cat file

prints the file and

cat file1 file2 >file3

concatenates the first two files and places the result on the third.

If no file is given, or if the argument ‘-‘ is encountered, cat reads from the standard input. Output is buffered in 512-byte blocks unless the standard output is a terminal or the -u option is present.

SEE ALSO

pr(1), cp(1)

BUGS

Beware of ‘cat a b >a’ and ‘cat a b >b’, which destroy input files before reading them.

Your task is to write the Unix V7 cat program. 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.

About these ads

Pages: 1 2

2 Responses to “Cat”

  1. My Haskell solution. Ignores the “-u” switch.


    import System.Environment
    import System.IO
    import Control.Exception

    parseCmd :: [String] -> IO [Handle]
    parseCmd [] = return []
    parseCmd ["-"] = return [stdin]
    parseCmd ("-u":xs) = parseCmd xs
    parseCmd xs = mapM (`openFile` ReadMode) xs

    main :: IO ()
    main = do
    args hGetContents h >>= putStr))

  2. Ok, something went wrong while posting. Let’s try again.

    import System.Environment
    import System.IO
    import Control.Exception
    
    
    parseCmd :: [String] -> IO [Handle]
    parseCmd []        = return []
    parseCmd ["-"]     = return [stdin]
    parseCmd ("-u":xs) = parseCmd xs
    parseCmd xs        = mapM (`openFile` ReadMode) xs
    
    main :: IO ()
    main = do
      args <- getArgs
      bracket (parseCmd args) (mapM_ hClose)
              (mapM_ (\h -> hGetContents h >>= putStr))
    

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 615 other followers

%d bloggers like this: