[Haskell-beginners] merge two files in to one file

Erik de Castro Lopo mle+hs at mega-nerd.com
Wed Oct 5 03:24:57 CEST 2011


kolli kolli wrote:

> all the lines of first file followed by all the lines of second file

Well, it can be as simple as:

    main :: IO ()
    main = do
        data1 <- readFile "firstfile"
        data2 <- readFile "secondfile"
        writeFile "output" (data1 ++ data2)

which should work fine for text files of arbitrary length. It won't
however work for binary files (due to text encoding issues). For that
try something like:

    import qualified Data.ByteString.Lazy as BSL

    main :: IO ()
    main = do
        data1 <- BSL.readFile "firstfile"
        data2 <- BSL.readFile "secondfile"
        BSL.writeFile "output" (BSL.concat [data1, data2])

In both cases, Haskell's lazy evaluation means that the program does
not need to read in the whole of each file, but will read both files
in chunks as well as writing the output file in chunks.

HTH,
Erik
-- 
----------------------------------------------------------------------
Erik de Castro Lopo
http://www.mega-nerd.com/



More information about the Beginners mailing list