0

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#)?

SealCuadrado
  • 749
  • 1
  • 10
  • 21
  • The name is always: `.`. What would you expect to be the name of a file system's root? – alk Oct 21 '13 at 15:26
  • The name of the root file system's root directory is `/` (aka `/.` or `/..`). The name of the root of a mounted file system's root directory is the basename of the mount point of the mounted file system. One name for the current directory is indeed `.`, but that isn't quite what the question asks for (more accurately, the title should be something like "Obtain the name of the directory entry in the parent directory that identifies the current directory". And I suspect you know most of that, but the OP may not. – Jonathan Leffler Oct 21 '13 at 16:32

3 Answers3

2

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).

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
0

you can parse the result of getcwd()

Balu
  • 2,247
  • 1
  • 18
  • 23
0

Maybe not the most elegant way, but this should work by using a combination of strchr() and memmove().

#include <stdio.h>
#include <string.h>

int main() {
  char *s;
  char buf[] = "/home/folder/include";

  s = strrchr (buf, '/');

  if (s != NULL) {
    memmove(s, s+1, strlen(s+1)+1);
    printf ("%s\n", s);
  }
 return 0;
}

prints include

EDIT: The following code is better and also calls getcwd()

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

int main() {

char buffer[200];   
char *s;

getcwd(buffer,sizeof(buffer));

s = strrchr(buffer, '/');

if (s != NULL) {
    printf ("%s\n", s+1);
}
return 0;
}
SealCuadrado
  • 749
  • 1
  • 10
  • 21
PhillipD
  • 1,797
  • 1
  • 13
  • 23