接受的答案包含两个错误(它将错误的值作为字符串长度传递给GETCWD,并留在C_NULL_CHAR)。这个答案纠正了这些错误,并使界面在 Fortran 中更有用。
基本思想是相同的:使用 C 调用 getcwd 或 _getcwd,并使用 Fortran 的 C 互操作性特性调用 C 包装器。在 Fortran 方面,包装子程序用于处理字符串长度,因此不必显式传递。
另外,C_INT 和 C_CHAR 不必与 Fortran 端需要的默认整数和默认字符相同(尽管实际上我不知道有任何系统 C_CHAR 和默认字符不同)。包装器也会转换那些。此外,从 C 返回的字符串包含终止符 C_NULL_CHAR,必须删除它才能使字符串在 Fortran 端可用。
C 代码:
#ifdef _WIN32
#include <direct.h>
#define GETCWD _getcwd
#else
#include <unistd.h>
#define GETCWD getcwd
#endif
/* Return 0 on success, 1 on error. */
int getCWDHelper(char *str, int len)
{
return GETCWD(str, len) != str;
}
Fortran 代码:
module cwd
use iso_c_binding, only: C_INT, C_CHAR, C_NULL_CHAR
implicit none
private
public :: getCWD
interface
function getCWDHelper(str, len) bind(C, name="getCWDHelper")
use iso_c_binding, only: C_INT, C_CHAR
integer(kind=C_INT) :: getCWDHelper
character(kind=C_CHAR), intent(out) :: str(*)
integer(kind=C_INT), value :: len
end function getCWDHelper
end interface
contains
! Writes the current working directory path into str.
! Returns 0 on success, or 1 on error.
function getCWD(str)
integer :: getCWD
character(*), intent(out) :: str
integer :: i, length
character(len=len(str), kind=C_CHAR) :: str_copy
! Call the C helper, passing the length as the correct int kind
getCWD = getCWDHelper(str_copy, len(str_copy, kind=C_INT))
if (getCWD /= 0) then
str = '' ! Error, clear the string
return
end if
! Copy the C_CHAR string to the output string,
! removing the C_NULL_CHAR and clearing the rest.
length = index(str_copy, C_NULL_CHAR) - 1
do i = 1, length
str(i:i) = char(ichar(str_copy(i:i)))
end do
str(length+1:) = ''
end function getCWD
end module
测试代码:
program test
use cwd, only: getCWD
implicit none
character(len=255) :: path
integer :: error
error = getCWD(path)
print *, error
if (error == 0) print *, path
end program
使返回值可分配并循环以获得足够的大小留给读者作为练习。