> Could somone please help me with some simple code for reading and writing
text
> files ???
> I need to save and open textfiles in my program.
>
>
> // Michael Medin
Hi Michael,
The following code read in a file, and sends it line by line to a
function processLine, and displays the output on the terminal.
(Try it in Hugs)
testIO :: IO ()
testIO =
do
fromHandle <- openFile "filename.txt" ReadMode
contents <- hGetContents fromHandle
putStr (unlines (processLine (lines contents)))
processLine :: String -> String
processLine s = s
You may change the processing of processLine to something
less stupid...
However my question is: How to do a little bit more complex IO:
Assume I have a file called 'filenames.txt' that contains a
list of filenames eg:
file1.txt
file2.txt
file3.txt
I now want to write a simple program, that prints out the first
line of every file mentioned in 'filenames.txt'.
I can start with:
module TestFile (
processFile )
where
import IO
testIO :: IO ()
testIO =
do
fromHandle <- openFile "filenames.txt" ReadMode
contents <- hGetContents fromHandle
putStr (unlines (processFiles (lines contents)))
processFiles :: [String] -> [String]
processFiles [] = []
processFiles (f:fs) = (processSingleFile f) : (processFiles fs)
processSingleFile :: String -> String
processSingleFile s =
do
inh <- openFile s ReadMode
cont <- hGetContents inh
return (head (lines cont))
Everybody immediately sees, that the last function 'processSingleFile'
is wrong! But how, has this example to be changed, to compile and
run successfully ??
Many thanks for all hints
Roland Senn e-mail: [EMAIL PROTECTED]