実行中のアプリへのフルパスを取得するコードは次のとおりです:
ウィンドウ:
char pBuf[256];
size_t len = sizeof(pBuf);
int bytes = GetModuleFileName(NULL, pBuf, len);
return bytes ? bytes : -1;
Linux:
int bytes = MIN(readlink("/proc/self/exe", pBuf, len), len - 1);
if(bytes >= 0)
pBuf[bytes] = '\0';
return bytes;
プログラムの最初の起動時に現在のディレクトリを取得すると、プログラムが起動されたディレクトリが効果的に取得されます。値を変数に格納し、後でプログラムで参照します。これは、現在の実行可能プログラム ファイルを保持するディレクトリとは異なります。必ずしも同じディレクトリではありません。誰かがコマンド プロンプトからプログラムを実行した場合、そのプログラムはから実行されます。 プログラム ファイルは別の場所にありますが、コマンド プロンプトの現在の作業ディレクトリです。
getcwd は POSIX 関数であり、すべての POSIX 準拠プラットフォームですぐにサポートされます。特別なことをする必要はありません (Unix では適切なヘッダー unistd.h を、Windows では direct.h をインクルードする以外は)。
C プログラムを作成しているため、システム内のすべてのプロセスによってリンクされるデフォルトの C ランタイム ライブラリにリンクされ (特別に細工された例外は回避されます)、デフォルトでこの関数が含まれます。 CRT は、基本的な標準準拠のインターフェイスを OS に提供するため、外部ライブラリとは見なされません。
Windows では、getcwd 関数は廃止され、_getcwd が使用されるようになりました。この方法で使用できると思います。
#include <stdio.h> /* defines FILENAME_MAX */
#ifdef WINDOWS
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif
char cCurrentPath[FILENAME_MAX];
if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath)))
{
return errno;
}
cCurrentPath[sizeof(cCurrentPath) - 1] = '\0'; /* not really required */
printf ("The current working directory is %s", cCurrentPath);
これは cplusplus フォーラムからのものです
Windows の場合:
#include <string>
#include <windows.h>
std::string getexepath()
{
char result[ MAX_PATH ];
return std::string( result, GetModuleFileName( NULL, result, MAX_PATH ) );
}
Linux の場合:
#include <string>
#include <limits.h>
#include <unistd.h>
std::string getexepath()
{
char result[ PATH_MAX ];
ssize_t count = readlink( "/proc/self/exe", result, PATH_MAX );
return std::string( result, (count > 0) ? count : 0 );
}
HP-UX の場合:
#include <string>
#include <limits.h>
#define _PSTAT64
#include <sys/pstat.h>
#include <sys/types.h>
#include <unistd.h>
std::string getexepath()
{
char result[ PATH_MAX ];
struct pst_status ps;
if (pstat_getproc( &ps, sizeof( ps ), 0, getpid() ) < 0)
return std::string();
if (pstat_getpathname( result, PATH_MAX, &ps.pst_fid_text ) < 0)
return std::string();
return std::string( result );
}