How to get the executable directory in Haskell?

I have a program that reads and writes a text file that exists in the same directory as the executable. To access this file, I call readFile "./file.txt"

This works when I run the executable from the directory in which it lives. However, if I cd to another directory and run the executable file (it is on my path), Haskell tries to get file.txt from the working directory in my terminal. How to make Haskell access to file.txt from the location of the executable, and not to my working directory. I don’t want to hardcode the absolute path, because I want the executable to be somewhat portable.

+4
source share
3 answers

Why not save the file in the official application directory? Then it does not matter what the current directory is. (See getAppUserDataDirectory .)

System.Directory has other useful directories and useful file system utilities. It is cross-platform in the sense that it knows where things should go according to your OS.

Reasoning:
If you save working data in the same directory as the executable file, only the one who has write permissions in this directory can run your program correctly. Only the superuser can write to directories like /usr/local/bin , and only the administrator can write to C:\Program Files\ . Using the User Application Catalog, anyone can run the application because the application data directory is user-specific and can be writable, so this is good practice.

Personally, I don’t like applications to clutter up my main user area with configuration data, but you want applications to offer my user area as the first suggestion to save some of my own content ( getHomeDirectory ). I suggested the user application data directory because you proposed the executable directory, so it sounded like configuration data.

+5
source

The right way to do this is to list file.txt in the data-files field of your .cabal file and use getDataFileName to get it. See Documentation

+8
source

The getExecutablePath function does what you ask. Unfortunately, it was only added to the System.Environment just released by GHC 7.6.1 , which has not yet been included in the Haskell platform .

EDIT: Since then, new Haskell platforms with this feature have been released.

+3
source

Source: https://habr.com/ru/post/1433503/


All Articles