Could you please tell me how to get the file separator of current operating system, for example \
in Windows and /
in Unix, in Fortran at run-time.
You can use Fortran 2003 Standard intrinsic procedure GET_ENVIRONMENT_VARIABLE
to do something like this. Example:
CHARACTER(LEN=99999) :: path
CHARACTER(LEN=1) :: path_separator
CALL GET_ENVIRONMENT_VARIABLE('PATH',path)
path_separator=path(1:1)
WRITE(*,*)'Path separator is ',path_separator
END
This program will output "/" as a path separator in UNIX or Linux. You could get this from other environment variables as well. Notice that this example is hardwired for UNIX/Linux. You would need a bit different logic to extract e.g. "\" for Windows, but I am not familiar with this system. I vaguely remember from Win95 having something like "c:\.....", so it is likely that in case of Windows you would look for "\" in path(3:3)
.
Hope this helps.
As far as I know the Fortran standard does not say anything about the file system path separator. The best I can suggest is to define a macro which defines the appropriate separator. For example
#if __unix__
character(len=1), parameter :: path_sep='/'
#elif _WIN32
character(len=1), parameter :: path_sep='\'
#else
#error "path_sep not defined. Set this constant for your system."
#endif
However, on Windows you can use either /
or \
as your path separator (try it!) so on most systems there is no need to do anything special with the path separator.
Note that you don't need to determine the path separator at run-time. Since you must recompile your Fortran source for each new system you want to run it on, you just need to ensure that the correct path separator is specified at compile time for each new system (the path separator won't change between runs of your program on the same system).
Using preprocessor macros like those above it the obvious way of doing this: you can just add a new #elif
clause for each new system you port your code to. This is alot easier than introducing picemeal solutions which check particular environment variables like the other answers suggest.
In addition the specifying the path separator you may also need to set parameters for other aspects of the operating system environment. For example, the current and parent directory characters (.
and ..
respectively under Windows and POSIX systems).
Finally, note that the preprocessor defines __unix__
and _WIN32
are widely used macros which indicate which system you are on and one, depending which system you are on, should be set by most compilers. If they are not set you can usually use the flag -D__unix__=1
or -D_WIN32=1
when you are compiling your source to set one of these macros. To preprocess your code using the -cpp
(gfortran) or -fpp
(ifort) command line options or change your source files extensions from .f
to .F
or from .f90
to .F90
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With