我正在尝试使用以下代码获取父目录的名称:

dirp=opendir(cur_spot);
printf("parent name: %s\n", readdir(dirp)->d_name);
closedir(dirp);

cur_spot持有“…”。
我在一个循环中这样做,它不断地向上爬升到根目录,我的输出顺序是:
.
.bash_logout
.
.
srv

我知道它的遍历是正确的,因为我正在一路上检查索引节点。
我需要用别的名字吗?
谢谢

最佳答案

我是根据sjs回答下的评论中的观点得出这个结论的:

#include <dirent.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <sys/stat.h>
#include <limits.h>
#include <errno.h>

int LookupName(const char* parent, ino_t ino, char *name, size_t size)
{
  DIR *dp = opendir(parent);
  if (!dp) return -1;

  int ret = -1;
  struct dirent *de;
  while (de = readdir(dp))
  {
    if (de->d_ino == ino)
    {
      strncpy(name, de->d_name, size);
      ret = 0;
      break;
    }
  }

  closedir(dp);
  if (ret == -1) errno = ENOENT;
  return ret;
}

int GetWorkdir(char *workdir, size_t size)
{
  struct stat st;
  if (stat(".", &st)) return -1;

  char path[PATH_MAX];
  strncpy(path, "..", sizeof(path));

  memset(workdir, '\0', sizeof(workdir));

  char name[PATH_MAX];
  while (1)
  {
    if (LookupName(path, st.st_ino, name, sizeof(name))) return -1;
    if (!strcmp(name, "..") || !strcmp(name, "."))
    {
      strncpy(name, "/", sizeof(name));
      strncat(name, workdir, sizeof(name));
      strncpy(workdir, name, size);
      break;
    }

    if (workdir[0] != '\0')
    {
      strncat(name, "/", sizeof(name));
    }

    strncat(name, workdir, sizeof(name));
    strncpy(workdir, name, size);

    if (stat(path, &st)) return -1;

    strncat(path, "/..", sizeof(path));
  }

  return 0;
}

int main(int argc, char **argv)
{
  char workDir[PATH_MAX];

  assert(!GetWorkdir(workDir, sizeof(workDir)));
  printf("%s\n", workDir);
}

09-06 10:34