你能告诉我如何在Fortran运行时获取当前操作系统的文件分隔符,例如Windows中的 \
和Unix中的 /
吗?
你能告诉我如何在Fortran运行时获取当前操作系统的文件分隔符,例如Windows中的 \
和Unix中的 /
吗?
#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
/
或\
作为路径分隔符(试试吧!),因此在大多数系统上,不需要对路径分隔符进行任何特殊处理。#elif
子句。这比引入检查特定环境变量的零散解决方案要容易得多,就像其他答案建议的那样。.
和..
)。__unix__
和_WIN32
是广泛使用的宏,它们指示您所在的系统,并且应该由大多数编译器设置其中之一,具体取决于您所在的系统。如果它们没有设置,您通常可以在编译源代码时使用标志-D__unix__=1
或-D_WIN32=1
来设置其中一个宏。要使用-cpp
(gfortran)或-fpp
(ifort)命令行选项预处理您的代码,或将源文件扩展名从.f
更改为.F
或从.f90
更改为.F90
。GET_ENVIRONMENT_VARIABLE
来实现类似的操作。例如: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
这个程序将在UNIX或Linux中输出“/”作为路径分隔符。您也可以从其他环境变量中获取这个值。请注意,此示例是为UNIX/Linux硬编码的。如果需要提取Windows中的“\”,则需要稍微不同的逻辑,但我不熟悉这个系统。我模糊地记得Win95有类似“c:\ .....”的东西,因此在Windows的情况下,您可能会在path(3:3)
中查找“\”。
希望这能帮到您。
get_environment_variable
中,它似乎会读取与path
(上面的变量)长度相同的字符,并且很乐意将环境变量截断为path
的长度。因此,至少在Unix系统上,您可以使用call get_environment_variable('PATH', path_separator)
来获取/
。 - Chrisexport DELIMITER='/'
在Unix中
现在只需使用'\'在Windows中创建相应的变量,就可以开始了。
如果您不想在Windows中设置全局变量,或者没有权限这样做,请将以下内容放入.bat文件中:
set DELIMITER=\
有关 set 的更多信息,请参见 http://www.ss64.com/nt/set.html 在使用 set 时,您可能需要从 CMD 运行 fortran 程序。
最后将以下内容放入您的 fortran 文件中
CHARACTER :: delimiter
CALL get_environment_variable('DELIMITER',delimiter)
function delimiter_detect() result(delim)
character(LEN=1) :: delim
character(LEN=258) :: path
integer :: ii, stat_out
call GET_ENVIRONMENT_VARIABLE('HOME',path,status=stat_out)
if (stat_out/=0) go to 999
! xxx path='xx\' ! alternate test
do ii=1, 258
delim=path(ii:ii)
if (delim=='/'.or.delim=='\') return
! ... Note: emacs does not recognize the second delimiter test
enddo
999 continue
write(*,'(1x,a/1x,a/1x,a)') 'Could not obtain home directory path.', &
'Restart program and manually insert path', &
'to folder/directory containing input files.'
stop
end function delimiter_detect
话虽如此,我还没有在Windows操作系统上测试过这个概念。