Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get absolute path of file or directory, that does *not* exist?

How can I determine the absolute path of a file or directory from a given relative path in C/C++ on GNU/Linux?
I know about realpath(), but it does not work on non-existing files.

Let's say the user enters ../non-existant-directory/file.txt, and the programs working directory is /home/user/.
What I need is a function that returns /home/non-existant-directory/file.txt.

I need this function to check if a given path is in a certain subdirectory or not.

like image 927
Fabian Henze Avatar asked Jun 14 '12 13:06

Fabian Henze


People also ask

How do I find the absolute path of a directory?

The pwd command displays the full, absolute path of the current, or working, directory.

How do I get absolute path in Linux?

The pwd command prints the current/working directory, telling where you are currently located in the filesystem. This command comes to your rescue when you get lost in the filesystem, and always prints out the absolute path.

How do you convert to absolute path?

The absolutePath function works by beginning at the starting folder and moving up one level for each "../" in the relative path. Then it concatenates the changed starting folder with the relative path to produce the equivalent absolute path.


1 Answers

Try realpath. If it fails, start removing path components from the end one at a time and retrying realpath until it succeeds. Then append the components you removed back onto the result of the successful realpath call.

If you're sure the containing directory exists and you just want to make a file there, you only have to remove at most one component.

Another approach would be to just create the file first, then call realpath.

like image 159
R.. GitHub STOP HELPING ICE Avatar answered Oct 18 '22 15:10

R.. GitHub STOP HELPING ICE