[Haskell-beginners] doesFileExist cannot get ~/blah_blah right

Brent Yorgey byorgey at seas.upenn.edu
Tue Apr 9 14:07:39 CEST 2013


On Mon, Apr 08, 2013 at 04:04:22PM -0700, Erlend Hamberg wrote:
> On 8 April 2013 15:45, Hong Yang <hyangfji at gmail.com> wrote:
> 
> > I got "not exists ..." from
> >
> >     fileExists <- doesFileExist "~/blah_blah"
> >     if fileExists then print "exists ..."
> >                      else print "not exists ..."
> >
> > using the directory-1.1.0.2 package, when ~/blah_blah does exist.
> >
> 
> When you type “~/blah_blah” in your shell, the *shell* will expand “~” to
> your home directory, so when you pass “~/foo” to a program, that program
> never sees “~/foo”, but “/home/user/foo”. In other words, “~/blah_blah”
> probably does *not* exist.
> 
> What you probably should do is to find the user's home directory and
> prepend that to “blah_blah”. You can find a user's homedir by calling
> `getHomeDirectory` from `System.Directory`:
> 
>     Prelude System.Directory> homedir <- getHomeDirectory
>     Prelude System.Directory> putStrLn $ homedir ++ "/blah_blah"
>     /Users/ehamberg/blah_blah

Also, since we are discussing portability, it's a much better idea to do

  homedir </> "blah_blah"

instead of homedir ++ "/blah_blah", since the former will use the
correct path separator character for whatever system it is compiled
on.

-Brent



More information about the Beginners mailing list