0

我已经看到了,并且我曾多次使用该函数cwd()来获取文件夹的绝对路径,但是有一个问题,那就是是否可以使用 C 来获取文件夹的名称

例如,假设我在这个文件夹上执行了一个程序:

/home/sealcuadrado/work1/include

如果我不为我的程序提供任何参数,我将使用cwd()并且肯定会获得该文件夹的绝对路径。

但我想要的只是实际文件夹的名称,在这种情况下包括. 这可以在 C 中完成吗(我在 Python 和 C# 中见过)?

4

3 回答 3

2

basename() 函数应用于 的结果getcwd()

另一种方法是获取当前目录的 inode 编号 ( .),然后打开并扫描父目录 ( ..) 以查找具有相应 inode 编号的名称。如果父目录包含 NFS 自动挂载点(例如主目录),这将变得很棘手;如果您不小心,您最终可能会自动挂载大量文件系统(这很慢而且几乎毫无意义)。

于 2013-10-21T15:14:50.893 回答
0

你可以解析 getcwd() 的结果

于 2013-10-21T15:20:15.867 回答
0

也许不是最优雅的方式,但这应该通过使用 strchr() 和 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;
}

印刷include

编辑:以下代码更好,并且还调用 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;
}
于 2013-10-21T15:26:49.470 回答