Cプログラムで現在のディレクトリを取得する方法は?
-
08-07-2019 - |
質問
プログラムを起動するディレクトリを取得する必要があるCプログラムを作成しています。このプログラムは、UNIXコンピューター用に作成されています。私は opendir()
と telldir()
を見てきましたが、 telldir()
は off_t(long int)
、それは本当に私を助けません。
現在のパスを文字列(char配列)で取得するにはどうすればよいですか?
解決
#include <unistd.h>
char *getcwd(char *buf, size_t size);
簡単な例:
#include <unistd.h>
#include <stdio.h>
#include <limits.h>
int main() {
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != NULL) {
printf("Current working dir: %s\n", cwd);
} else {
perror("getcwd() error");
return 1;
}
return 0;
}
他のヒント
getcwd
のマニュアルページをご覧ください。
質問にはUnixというタグが付けられていますが、ターゲットプラットフォームがWindowsの場合、人々は質問にアクセスすることもできます。Windowsの答えは GetCurrentDirectory()
関数:
DWORD WINAPI GetCurrentDirectory(
_In_ DWORD nBufferLength,
_Out_ LPTSTR lpBuffer
);
これらの回答は、CコードとC ++コードの両方に適用されます。
#include <stdio.h> /* defines FILENAME_MAX */
//#define WINDOWS /* uncomment this line to use it for windows.*/
#ifdef WINDOWS
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif
int main(){
char buff[FILENAME_MAX];
GetCurrentDir( buff, FILENAME_MAX );
printf("Current working dir: %s\n", buff);
return 1;
}
getcwd(3)
はMicrosoftのlibcでも利用可能です: getcwd(3)、期待どおりに動作します。
-loldnames
(oldnames.lib、ほとんどの場合自動的に行われます)とリンクするか、 _getcwd()
を使用する必要があります。接頭辞なしのバージョンはWindows RTでは使用できません。
所属していません StackOverflow