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

后端 未结 7 1785
轻奢々
轻奢々 2020-12-05 07:33

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

相关标签:
7条回答
  • 2020-12-05 08:02

    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 .
    
    0 讨论(0)
  • 2020-12-05 08:05

    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.

    0 讨论(0)
  • 2020-12-05 08:05
    // 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();
    }
    
    0 讨论(0)
  • 2020-12-05 08:06

    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.

    0 讨论(0)
  • 2020-12-05 08:18

    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; 
    } 
    
    0 讨论(0)
  • 2020-12-05 08:26

    Try realpath:

    $ man realpath
    

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

    0 讨论(0)
提交回复
热议问题