17

如何从 GNU/Linux 上的 C/C++ 中的给定相对路径确定文件或目录的绝对路径?
我知道realpath(),但它不适用于不存在的文件。

假设用户进入../non-existant-directory/file.txt,程序工作目录是/home/user/.
我需要的是一个返回的函数/home/non-existant-directory/file.txt

我需要这个函数来检查给定的路径是否在某个子目录中。

4

2 回答 2

10

试试realpath。如果失败,则开始一次从末尾删除路径组件并重试realpath直到成功。然后将您删除的组件附加到成功realpath调用的结果中。

如果您确定包含目录存在并且只想在其中创建文件,则最多只需要删除一个组件。

另一种方法是先创建文件,然后调用realpath.

于 2012-06-14T13:42:15.830 回答
0

正如@R.. GitHub 所指出的,您可以在realpath(). 这是一个示例函数,用于realpath()确定存在的路径部分的规范形式,并将路径的不存在部分附加到它。

由于realpath()操作 C 风格的字符串,我决定在这里也使用它们。但是该功能可以很容易地重写以使用std::string(只是不要忘记canonical_file_path将其复制到后释放std::string!)。

请注意,重复的“/”条目不会从不存在的路径部分中删除;它只是附加到确实存在的部分的规范形式。

////////////////////////////////////////////////////////////////////////////////
// Return the input path in a canonical form. This is achieved by expanding all
// symbolic links, resolving references to "." and "..", and removing duplicate
// "/" characters.
//
// If the file exists, its path is canonicalized and returned. If the file,
// or parts of the containing directory, do not exist, path components are
// removed from the end until an existing path is found. The remainder of the
// path is then appended to the canonical form of the existing path,
// and returned. Consequently, the returned path may not exist. The portion
// of the path which exists, however, is represented in canonical form.
//
// If successful, this function returns a C-string, which needs to be freed by
// the caller using free().
//
// ARGUMENTS:
//   file_path
//   File path, whose canonical form to return.
//
// RETURNS:
//   On success, returns the canonical path to the file, which needs to be freed
//   by the caller.
//
//   On failure, returns NULL.
////////////////////////////////////////////////////////////////////////////////
char *make_file_name_canonical(char const *file_path)
{
  char *canonical_file_path  = NULL;
  unsigned int file_path_len = strlen(file_path);

  if (file_path_len > 0)
  {
    canonical_file_path = realpath(file_path, NULL);
    if (canonical_file_path == NULL && errno == ENOENT)
    {
      // The file was not found. Back up to a segment which exists,
      // and append the remainder of the path to it.
      char *file_path_copy = NULL;
      if (file_path[0] == '/'                ||
          (strncmp(file_path, "./", 2) == 0) ||
          (strncmp(file_path, "../", 3) == 0))
      {
        // Absolute path, or path starts with "./" or "../"
        file_path_copy = strdup(file_path);
      }
      else
      {
        // Relative path
        file_path_copy = (char*)malloc(strlen(file_path) + 3);
        strcpy(file_path_copy, "./");
        strcat(file_path_copy, file_path);
      }

      // Remove path components from the end, until an existing path is found
      for (int char_idx = strlen(file_path_copy) - 1;
           char_idx >= 0 && canonical_file_path == NULL;
           --char_idx)
      {
        if (file_path_copy[char_idx] == '/')
        {
          // Remove the slash character
          file_path_copy[char_idx] = '\0';

          canonical_file_path = realpath(file_path_copy, NULL);
          if (canonical_file_path != NULL)
          {
            // An existing path was found. Append the remainder of the path
            // to a canonical form of the existing path.
            char *combined_file_path = (char*)malloc(strlen(canonical_file_path) + strlen(file_path_copy + char_idx + 1) + 2);
            strcpy(combined_file_path, canonical_file_path);
            strcat(combined_file_path, "/");
            strcat(combined_file_path, file_path_copy + char_idx + 1);
            free(canonical_file_path);
            canonical_file_path = combined_file_path;
          }
          else
          {
            // The path segment does not exist. Replace the slash character
            // and keep trying by removing the previous path component.
            file_path_copy[char_idx] = '/';
          }
        }
      }

      free(file_path_copy);
    }
  }

  return canonical_file_path;
}
于 2020-03-30T02:54:05.740 回答