196

プログラムが開始されるディレクトリを取得する必要があるCプログラムを作成しています。このプログラムは UNIX コンピュータ用に書かれています。opendir()とを見てきましたがtelldir()、をtelldir()返すoff_t (long int)ので、本当に役に立ちません。

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

4

7 に答える 7

349

をご覧になりました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;
}
于 2008-11-18T11:38:24.747 に答える
60

のマニュアルページを調べてくださいgetcwd

于 2008-11-18T11:37:30.257 に答える
3
#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;
}
于 2017-12-18T22:39:39.670 に答える