Monday 30 May 2016

Haskell: Working with temporary files

Most of the times, real world applications require creating temporary files. These files may be used to store intermediate data. Haskell provides number of functions to work with temporary files. Following table summarizes the functions provided by Haskell.

Function
Signature
Description
openTempFile
openTempFile :: FilePath -> String -> IO (FilePath, Handle)
Creates a temporary file in ReadWrite mode. FilePath specifies the Directory in which to create the file. String represents the file name template. If the template is "abc.tmp" then the created file will be "abcXXX.tmp" where XXX is some random number. The file created by this method is not deleted automatically, you need to delete the file manually, once you are done with it. By default permissions are given to the user who creates the file, So only current user can read/write it.
openBinaryTempFile
openBinaryTempFile :: FilePath -> String -> IO (FilePath, Handle)
Similar to openTempFile, but opens the file in binary mode
openTempFileWithDefaultPermissions
openTempFileWithDefaultPermissions :: FilePath -> String -> IO (FilePath, Handle)
Similar to openTempFile, but uses the default file permissions.
openBinaryTempFileWithDefaultPermissions
openBinaryTempFileWithDefaultPermissions :: FilePath -> String -> IO (FilePath, Handle)
Similar to openBinaryTempFile, but uses the default file permissions


FileUtil.hs
import System.IO

main = 
    do
        putStrLn "Enter directory to create temporary file"
        directory <- getLine

        putStrLn "Enter temporary file template"
        fileName <- getLine

        (filePath, fileHandle) <- openTempFile directory fileName

        hPrint fileHandle "Hari Krishna"
        hPrint fileHandle "Gurram"
        hPrint fileHandle 523169
        hPrint fileHandle 12345.6

        hClose fileHandle

$ runghc FileUtil.hs
Enter directory to create temporary file
/Users/harikrishna_gurram
Enter temporary file template
abc.tmp

$ cd /Users/harikrishna_gurram/
$
$ ls abc*tmp
abc16807282475249.tmp
$
$ cat abc16807282475249.tmp
"Hari Krishna"
"Gurram"
523169
12345.6


Observe the output, it creates a temporary file ‘abc16807282475249.tmp’.

Re run FileUtil.hs.
$ runghc FileUtil.hs
Enter directory to create temporary file
/Users/harikrishna_gurram
Enter temporary file template
abc.tmp

This time it creates another temporary file, It keeps the old temporary file until you remove.



Previous                                                 Next                                                 Home

No comments:

Post a Comment