Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get absolute path of current source file in Haskell

Tags:

haskell

Is it possible to get the absolute path of the current source file in Haskell?

I could only find one relevant function: getCurrentDirectory from System.Directory, but it "returns an absolute path to the current directory of the calling process.", not the path of the current file.

(I need it to read sample inputs which are located in the same folder as the source file; If there's any better way to do it, that will be helpful too!)

like image 233
Dogbert Avatar asked Jan 09 '14 08:01

Dogbert


People also ask

How do I find absolute path?

You can determine the absolute path of any file in Windows by right-clicking a file and then clicking Properties. In the file properties first look at the "Location:" which is the path to the file.

What is the absolute path of a file?

An absolute path always contains the root element and the complete directory list required to locate the file. For example, /home/sally/statusReport is an absolute path. All of the information needed to locate the file is contained in the path string.

How do you get the absolute path of a file in flutter?

You can try to use path_provider plugin to access some directories or you can access to a file by create path from it's parts (like app directory + internal directory + filename).


2 Answers

You can use CPP. If you compile this file

{-# LANGUAGE CPP #-}
main = print __FILE__

it will print the path to the source as you passed it to ghc – which may or may not be the full path, though:

/tmp $ ghc --make mypath.hs 
[1 of 1] Compiling Main             ( mypath.hs, mypath.o )
Linking mypath ...
/tmp $ ./mypath 
"mypath.hs"
/tmp $ ghc --make /tmp/mypath.hs 
Linking /tmp/mypath ...
/tmp $ ./mypath 
"/tmp/mypath.hs"
like image 136
Joachim Breitner Avatar answered Sep 27 '22 21:09

Joachim Breitner


As an alternative, the file-embed package can be used here. It uses template haskell to embed files/directories.

This can be very useful to embed resources or configs in the executable. It may not be advisable to read the sample input this way though. data-files in cabal might be better alternative as already pointed out earlier in this thread.

like image 27
Yogesh Sajanikar Avatar answered Sep 27 '22 22:09

Yogesh Sajanikar