View Category

Read the contents of a file into a string

haskell
readFile "c:/tmp/myFile.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
haskell
import Data.List

prefixWithNumber str n = show n ++ "> " ++ str

numberStrings (x:xs) n = prefixWithNumber x n : (numberStrings xs (n+1))
numberStrings [] n = []

main = do
str <- readFile "prefix.hs"
putStrLn (intercalate "\n" (numberStrings (lines str) 1))
prefix n str = show n ++ "> " ++ str

main = readFile "prefix.hs" >>=
putStr . unlines . zipWith prefix [1..] . lines

Write a string to a file

haskell
writeFile "filename" "stringe"

Append to a file

haskell
appendfile "filename" "string"

Process each file in a directory

haskell
import System.Directory
import Control.Monad

process filename = putStrLn filename

main = getDirectoryContents "." >>=
filterM doesFileExist >>=
mapM_ process

Process each file in a directory recursively

haskell
import System.Directory (doesFileExist, getDirectoryContents)
import System.FilePath ((</>))

process :: FilePath -> IO ()
process filename = putStrLn filename

mapDir :: (FilePath -> IO ()) -> FilePath -> IO ()
mapDir proc fp = do
isFile <- doesFileExist fp -- is a file of fp
if isFile then proc fp -- process the file
else getDirectoryContents fp >>=
mapM_ (mapDir proc . (fp </>)) . filter (`notElem` [".", ".."])

main = mapDir process "."