Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine absolute path and relative path to get a new absolute path

Tags:

I'm writing a program in which one of the components must be able to take a path it is given (such as /help/index.html, or /help/) and a relative path based on that location, (such as ../otherpage/index.html, or sub/dir/of/help/, or help2.html) and produce the absolute path implied by the relative path. Consider the following directory tree.

/
index.html
content.txt
help/
    help1.html
    help2.html

The file index.html contains a link like help/help1.html. The program is passed / or /index.html, and combines it with help/help1.html to get /help/help1.html.

Similarly, the file /help/help1.html has the link ../content.txt, from which the program needs to return /content.txt. Is there a reasonable way to do this?

Thank you. :)

Edit: Thank you to Stephen Weinberg! For everyone from the future, here's the code I used.

func join(source, target string) string {
    if path.IsAbs(target) {
        return target
    }
    return path.Join(path.Dir(source), target)
}
like image 514
Alexander Bauer Avatar asked Oct 25 '12 22:10

Alexander Bauer


People also ask

Can absolute path and relative path be the same?

In simple words, an absolute path refers to the same location in a file system relative to the root directory, whereas a relative path points to a specific location in a file system relative to the current directory you are working on.

What is path combine?

Combines two strings into a path. Combine(String, String, String) Combines three strings into a path. Combine(String, String, String, String) Combines four strings into a path.

How do you use absolute and relative paths?

An absolute path is defined as specifying the location of a file or directory from the root directory(/). In other words,we can say that an absolute path is a complete path from start of actual file system from / directory. Relative path is defined as the path related to the present working directly(pwd).


1 Answers

The path.Join when used with path.Dir should do what you want. See http://golang.org/pkg/path/#example_Join for an interactive example.

path.Join(path.Dir("/help/help1.html"), "../content.txt")

This will return /content.txt.

like image 199
Stephen Weinberg Avatar answered Sep 25 '22 08:09

Stephen Weinberg