Search code examples
haskellio

get file content if file exists or default String


I check doesFileExist filePath but how can i use handle <- openFile filePath ReadMode only when the file exists

Or how can i get a default string when file does not exist?

getFileContent filePath = do
    handle <- openFile filePath ReadMode
    content <- hGetContents handle
    return content

main = do
    blacklistExists <- doesFileExist "./blacklist.txt"
    let fileContent = if not blacklistExists
            then ""
            else getFileContent "./blacklist.txt"

    putStrLn fileContent

Solution

  • Like this:

    import Control.Exception
    
    getFileContentOrElse :: String -> FilePath -> IO String
    getFileContentOrElse def filePath = readFile filePath `catch`
        \e -> const (return def) (e :: IOException)
    
    main = getFileContentOrElse "" "blacklist.txt" >>= putStrLn
    

    The const _ (e :: IOException) bit is just to be able to give e a type annotation, so that catch knows which Exception instance to use.