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.
Haskell : doesFileExist. Description: The operation doesFileExist returns True if the argument file exists and is not a directory, and False otherwise.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With