Question

I want to know if it is a problem only for me, and how to get through this.

I am now in the $HOME directory, and I can touch aaa to create one file.

Then I launch ghci. I can import System.Directory to import this package.

Now the problem occurs. If I try doesFileExist aaa, I will get True because it is really there. If I try doesFileExist ~/aaa, I will get False!!!

What is the problem then? Edit me if you find it is not clear. Thanks.

Was it helpful?

Solution 4

If you want to expand a ~ like the shell does, you can define a function

expandHome :: FilePath -> FilePath -> FilePath
expandHome home ('~':xs) = home ++ xs
expandHome home path     = path

This can be called as

λ> h <- getHomeDirectory
λ> expandHome h "~/temp"
"/home/kqr/temp"

OTHER TIPS

Haskell, like quite a few other languages, doesn't parse the ~ as home directory. ~ is just a common unix shell feature. So it's looking for a literal directory named ~.

Instead try

import System.FilePath.Posix
import System.Directory

homeDirFile :: FilePath -> IO FilePath
homeDirFile p = fmap (</>p) getHomeDirectory

main = homeDirFile "aaa" >>= doesFileExist >>= print

The ~ expansion is not performed because it is a feature of the shell. doesFileExist "/home/your-user/aaa" should work. You might want to use getHomeDirectory from System.Directory.

You can interact with system shell via command-qq.

> import System.Command.QQ
> :set -XQuasiQuotes 
> [sh|touch ~/aaa|] :: IO ()

And here you've got ~/aaa file created.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top