Siva Kannan
Siva Kannan

Reputation: 2471

How to get the current working directory(current working folder) name instead of the path name?

I know how to get CWD's path name through the getcwd function , and I'm using the strtok function to get the directory name(means current working folder) , is there anything available to get this thing through a simple query or a function?

Upvotes: 0

Views: 1016

Answers (3)

alk
alk

Reputation: 70911

If getcwd() returns "/this/is/my/cwd" and you want just "cwd" then you might like to use basename() on what was returned by getcwd().

#include <unistd.h> /* for getcwd() */
#include <libgen.h> /* for basename() */

[...]

  char cwd[PATH_MAX] = "";
  char * cwd_base = NULL;

  if (NULL == getcwd(cwd, sizeof(cwd)))
  {
    perror("getcwd() failed");
  }
  else
  {
    cwd_base = basename(cwd);
  }

  if (NULL != cwd_base)
  {
    printf("The current working directory's base name is '%s'.\n", cwd_base);
  }

Upvotes: 4

Carmol
Carmol

Reputation: 11

Use whatever comes handy:

For this particular case, all of those are sufficiently easy to use. And if you use such a lot, factor it out into a "helper" subroutine.

Upvotes: 0

unwind
unwind

Reputation: 399803

I would use strrchr() using the platform's directory separator, not strtok().

Of course, "current working folder" typically needs to be a full absolute path in order to be useful for file-system access.

Upvotes: 3

Related Questions