質問

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

役に立ちましたか?

解決

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

他のヒント

you can parse the result of getcwd()

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;
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top