Cプログラムで現在のディレクトリを取得するには?

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 によって提案されたリンクで、Google 検索 'site:microsoft.com getcurrentdirectory' で現在のトップの選択肢として確認されました。