如何在 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
How to get the absolute path for a given relative path programmatically in Linux?
提问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 _fullpath
of Windows in Linux?
在 Windows 的情况下,我们有_fullpath()
API。换句话说,我的意思是什么是类似于_fullpath
Linux 中 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
回答by Martin Wickman
回答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();
}