[Haskell-beginners] please critique my first stab at systems programming

Sean Perry shaleh at speakeasy.net
Thu Apr 14 12:14:59 CEST 2011

The idea is to walk the disk looking for a signature, say NTFS or EXT. Since we do not know where the block containing this identifier is, we read the blocks in one at a time.

Long term I would like to support command line arguments for the name of the file and the offset to start looking.

Comments on style, idioms, etc. welcomed. I am particularly interested in the hIsEOF check and if there is a better way to handle that.

import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC
import IO
import System.IO

chunkSize = 512

searchForPattern handle pat = searchForPattern' 0 handle pat                       

searchForPattern' index handle pat = do
    eof <- hIsEOF handle
    if eof then return Nothing
      else do
        bytes <- B.hGet handle chunkSize
        case BC.breakSubstring pat bytes of
          (x, y) | BC.null y -> searchForPattern' (index + 1) handle pat
                 | otherwise -> return (Just index)

main = do 
    fromHandle <- openBinaryFile "blocks" ReadMode
    result <- searchForPattern fromHandle (BC.pack "PART")
    case result of
      Nothing -> putStr "Not Found.\n"
      Just n  -> putStr $ "Found at " ++ show n ++ ".\n"
    hClose fromHandle
    putStr "Done.\n"

More information about the Beginners mailing list