如何在 Linux 中以编程方式获取给定相对路径的绝对路径?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2341808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 19:48:31  来源:igfitidea点击:

How to get the absolute path for a given relative path programmatically in Linux?

clinuxrelative-pathabsolute-path

提问by Jay

How to get the absolute path for a given relative path programmatically in Linux?

如何在 Linux 中以编程方式获取给定相对路径的绝对路径?

Incase of Windows we have the _fullpath()API. In other words, I mean what is analogous API to _fullpathof Windows in Linux?

在 Windows 的情况下,我们有_fullpath()API。换句话说,我的意思是什么是类似于_fullpathLinux 中 Windows 的API ?

采纳答案by unwind

As Paul mentioned, use realpath(). Please note though, that since many file systems in Linux support hard links, any given directory can have a number of different absolute paths.

正如保罗所说,使用realpath(). 不过请注意,由于 Linux 中的许多文件系统都支持硬链接,因此任何给定的目录都可以有许多不同的绝对路径。

回答by Paul R

Try realpath:

尝试真实路径

$ man realpath

This is also available in BSD, OS X, et al.

这也适用于 BSD、OS X 等。

回答by Otto Allmendinger

There is the realpathfrom stdlib.h

realpath来自stdlib.h

回答by Martin Wickman

Check out the realpathfunction.

查看realpath函数。

#include <stdlib.h> 
#include <stdio.h> 
#include <linux/limits.h>
int main() 
{ 
        char resolved_path[PATH_MAX]; 
        realpath("../../", resolved_path); 
        printf("\n%s\n",resolved_path); 
        return 0; 
} 

回答by Zebooka

The is also another useful way, like "readlink -m $filename"

这也是另一种有用的方法,例如“readlink -m $filename”

First of all, it works without requirement for target file to exist. Secondly, it will handle symlinks and get really real path.

首先,它不需要目标文件存在就可以工作。其次,它将处理符号链接并获得真正的路径。

回答by Lionel

Running on RedHat 5.3, realpath doesn't exist but readlink is installed. You can use it on relative paths and symlinks, plus it will resolve symlinks recursively for you. It's thus a better option that realpath in my opinion

在 RedHat 5.3 上运行,realpath 不存在,但安装了 readlink。您可以在相对路径和符号链接上使用它,而且它会为您递归解析符号链接。因此,在我看来,realpath 是一个更好的选择

readlink -f .

回答by Bill Moore

// For C++ with Gnome Gtkmm3 libraries
#include <glibmm.h>
#include <giomm.h>

  string PathRel2Abs(string relpath) {
  Glib::RefPtr<Gio::File> file = Gio::File::create_for_path(relpath);
  return file->get_path();
}