質問

プログラムを起動するディレクトリを取得する必要があるCプログラムを作成しています。このプログラムは、UNIXコンピューター用に作成されています。私は opendir() telldir()を見てきましたが、 telldir() off_t(long int)、それは本当に私を助けません。

現在のパスを文字列(char配列)で取得するにはどうすればよいですか?

役に立ちましたか?

解決

getcwd()をご覧になりましたか

#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 ++コードの両方に適用されます。

user4581301 によって提案されたリンク/ 31487046 / getting-the-output-of-cd-or-simply-getting-the-current-directory#comment50938605_31487046 ">コメントを別の質問に追加し、Google検索の「サイト:microsoft.com getcurrentdirectory '。

#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では使用できません。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top