How to get the absolute path for a given relative path programmatically in Linux?
Incase of Windows we have the _fullpath()
API. In other words, I mean what is analogous API to _fullpath
of Windows in Linux?
How to get the absolute path for a given relative path programmatically in Linux?
Incase of Windows we have the _fullpath()
API. In other words, I mean what is analogous API to _fullpath
of Windows in Linux?
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
resolves the name in the way you would expect - by (recursively) flattening out /../
and /./
components and resolving symlinks. The "multiple paths" issue just means that the name you get out at the end isn't necessarily unique for a given file (since a file does not necessarily have a single "true name"). –
Bullough Check out the realpath function.
#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;
}
realpath
which will most likely write beyond the buffer size (since it requires a length of PATH_MAX). Even if the program doesn't crash, this code could lead to security vulnerabilities depending on the variable layout, if an adversary can control the original path to be resolved. The manual recommends passing NULL as a second parameter and letting realpath
allocate memory to ensure no issues with PATH_MAX definitions, starting with POSIX 2008. –
Berryman There is the realpath
from stdlib.h
realpath
is in stdlib.h
. Surely that can't be true, considering that realpath
is not part of the C library. Lo and behold, it's true. I'm dumbfounded. What's a well-formed program that defines its own function named realpath
to do? Those POSIX guys have run amok! Amok I say! –
Horrible _XOPEN_SOURCE
), they should be OK. –
Bullough 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
readlink -f .
The is also another useful way, like "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.
// 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();
}
© 2022 - 2024 — McMap. All rights reserved.
c
, this is probably a duplicate of #229512 – Stretcher