Search code examples
csystem-callsgetcwd

Obtain the name of the current directory (not the path)


I had seen, and I had used a couple of time the function cwd() to get the absolute path of a folder, but there's a question, and that's if it's possible with C to get just the name of a folder.

For example, let's suppose that I execute a program on this folder:

/home/sealcuadrado/work1/include

If I don't give any arguments to my program, I will use cwd() and surely I will get the absolute path to that folder.

But what I want is just the name of the actual folder, in this case include. Can this be done in C (i had seen in in Python and C#)?


Solution

  • Apply the basename() function to the result of getcwd().

    An alternative is to mess around getting the inode number of the current directory (.) and then open and scan the parent directory (..) looking for the name with the corresponding inode number. That gets tricky if the parent directory contains NFS auto-mount points (home directories, for example); you can end up auto-mounting an awful lot of file systems if you aren't careful (which is slow and mostly pointless).