7

GNU Fortran コンパイラの GNU 拡張機能GETCWD()は、現在の作業ディレクトリを取得するサブルーチンを提供します。ただし、私のコードはコンパイラにも移植できる必要があり、ifortF2003nagforの機能を使用しています。

GETCWD()では、 F2003 以降の代替手段はありますか?

私はここに標準を持っていますが、かなり大きいので、しばらく試してみましたが、有用なものは何も見つかりませんでした...

4

3 に答える 3

7

コメントに記載されているように、get_environment_variable標準の Fortran (F2008 13.7.67 など) を使用できます。$PWDこのサンプル プログラムは、実行可能ファイルを呼び出したときにシェルが存在するディレクトリを含むの値を照会します。

program test
 implicit none
 character(len=128) :: pwd
 call get_environment_variable('PWD',pwd)
 print *, "The current working directory is: ",trim(pwd)
end program

そしてその出力:

casey@convect code % pwd
/home/casey/code
casey@convect code % so/getpwd 
 The current working directory is: /home/casey/code

これは標準の Fortran ですが、その移植性は、この変数を設定する Unix および Unix に似たシェルに限定されます。

標準的だが醜い(私の意見では)別のオプションはexecute_command_line、作業ディレクトリを一時ファイル(例:)に出力できるコマンドを実行し、pwd > /tmp/mypwdそのファイルを読み取ることです。

于 2015-05-16T19:12:28.737 に答える
6

を使用して、対応する関数ISO_C_Bindingを呼び出すこともできます。C

cwd.c:

#ifdef _WIN32
/* Windows */
#include <direct.h>
#define GETCWD _getcwd

#else
/* Unix */
#include <unistd.h>
#define GETCWD getcwd

#endif

void getCurrentWorkDir( char *str, int *stat )
{
  if ( GETCWD(str, sizeof(str)) == str ) {
    *stat = 0;
  } else {
    *stat = 1;
  }
}

test.F90:

program test
 use ISO_C_Binding, only: C_CHAR, C_INT
 interface
   subroutine getCurrentWorkDir(str, stat) bind(C, name="getCurrentWorkDir")
     use ISO_C_Binding, only: C_CHAR, C_INT
     character(kind=C_CHAR),intent(out) :: str(*)
     integer(C_INT),intent(out)         :: stat
    end subroutine
  end interface
  character(len=30)   :: str
  integer(C_INT)      :: stat

  str=''
  call getCurrentWorkDir(str, stat)
  print *, stat, trim(str)

end program

このコードは、Windows および Unix 派生物 (Linux、OSX、BSD など) で有効です。

于 2015-05-16T19:19:22.753 に答える