Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a file and its parent directories in Haskell?

I want to write content to a file by a non-trivial path and create all parent directories if they don't exist. So the following code:

mkFile "foo/bar/baz/quux.txt"

will create all directories foo/, foo/bar/ and foo/bar/baz/ if they don't exist (and the file quux.txt as well of course). What is the easiest way to implement such a function? Ideally, I would like to see a solution that uses only directory and filepath libraries.

like image 640
Shersh Avatar asked Nov 03 '19 16:11

Shersh


People also ask

Does file exist in Haskell?

Haskell : doesFileExist. Description: The operation doesFileExist returns True if the argument file exists and is not a directory, and False otherwise.


1 Answers

I'm trying to find the easiest way for this but can't find any. The only way is to implement our own function based on your needs. Fortunately, this is using System.Directory and System.FilePath.Posix libraries only.

import Prelude

import System.Directory (createDirectoryIfMissing)
import System.FilePath.Posix (takeDirectory)

main :: IO ()
main = createAndWriteFile "foo/bar/baz/quux.txt" "something"

createAndWriteFile :: FilePath -> String -> IO ()
createAndWriteFile path content = do
  createDirectoryIfMissing True $ takeDirectory path

  writeFile path content

Below is the result based on the code above.

foo
└── bar
    └── baz
        └── quux.txt

You may edit the code however you like.

like image 62
wisn Avatar answered Oct 11 '22 08:10

wisn