Accessing a file in user's home directory

Hello all,

I have a question about file/directory handling in Fortran. How should a file located in the user’s home directory be accessed from a Fortran program? If I define a file name as follows, the program always stores it into the same directory where the binary is located.

character(len=*), parameter :: FILENAME = 'file.txt'

I tried the usual Unix convention '~/file.txt', but it does not seem to work (files can’t be created). Is there some better way than just hard-coding the entire file path?

Background: I’m developing a note keeping application called fnote that should have its data stored at a fixed location (home dir).

Thanks in advance!

Hi @art-rasa ,
see the man bash section Tilde Expansion. The tilde is a kind of shortcut in bash for the HOME environment variable. So you can not use it in Fortran which considers it as a simple character.

You should read your environment variable HOME from your program:
https://gcc.gnu.org/onlinedocs/gfortran/GET_005fENVIRONMENT_005fVARIABLE.html
You have the example at the end of the page.

2 Likes

The OPEN statement will look for file.txt in the current working directory, which may differ from the directory of the binary.

2 Likes

@vmagnin
Thanks. It is exactly the information I was looking for.

@Beliavsky
Indeed, that’s a good point. When I run the program with “fpm run” it creates the file in the current (project root) directory.

You might be interested in using stdlib_os here:

This allows you to know what your current OS is and than chose the correct path to store your app specific data, which would probably be $HOME/.local/share/fnote on Unix systems and %APPDATA%\local\fnote on Windows (using APPDATA on Windows is easier than HOMEDIR because it already includes the drive letter which is absent in HOMEDIR and therefore has to be queried separately).

1 Like

Hello,

A recent discussion in c.l.f raised a similar issue. The thread is:
https://groups.google.com/g/comp.lang.fortran/c/KYnTjAYYJ6k
How to tell what operating system a Fortran executable is running on?

Then, I wrote a Fortran program that locates the user home directory in
various environments, ie Linux, macOS, Windows, and so on. The
program itself is dummy. You simply copy paste the routines you want,
see Hardcode or find at Runtime OS Name and File Separator in Fortran (by m_sys.java). · GitHub

Regards,
Ev. Drikos

1 Like