Cookbook/Files: Difference between revisions
< Cookbook
No edit summary |
No edit summary |
||
Line 39: | Line 39: | ||
TODO | TODO | ||
= Writing a filter = | |||
Using [http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:interact interact], you can easily do things with stdin and stdout. | Using [http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:interact interact], you can easily do things with stdin and stdout. | ||
Line 54: | Line 54: | ||
</haskell> | </haskell> | ||
= Logging to a file = | |||
TODO | TODO |
Revision as of 10:35, 23 April 2009
Reading from a file
The System.IO library contains the functions needed for file IO. The program below displays the contents of the file c:\test.txt.
import System.IO
main = do
h <- openFile "c:\\test.txt" ReadMode
contents <- hGetContents h
putStrLn contents
hClose h
The same program, with some higher-lever functions:
main = do
contents <- readFile "c:\\test.txt"
putStrLn contents
Writing to a file
The following program writes the first 100 squares to a file:
-- generate a list of squares with length 'num' in string-format.
numbers num = unlines $ take num $ map (show . \x -> x*x) [1..]
main = do
writeFile "test.txt" (numbers 100)
putStrLn "successfully written"
This will override the old contents of the file, or create a new file if the file doesn't exist yet. If you want to append to a file, you can use appendFile
.
Creating a temporary file
TODO
Writing a filter
Using interact, you can easily do things with stdin and stdout.
A program to sum up numbers:
main = interact $ show . sum . map read . lines
A program that adds line numbers to each line:
main = interact numberLines
numberLines = unlines . zipWith combine [1..] . lines
where combine lineNumber text = concat [show lineNumber, " ", text]
Logging to a file
TODO