- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Golang program to get the relative path from two absolute paths
To get the relative path from two absolute paths in golang, we use filepath and string packages. Relative paths tell the location of file with respect to present working directory whereas absolute paths tell the location of file starting from root directory. In the first method we will use filepath package functions and in the second method we will use strings package function.
Method 1: Using Filepath Package
In this program, the base name of the file, which is the file name without the directory path, is extracted using the filepath.Base function from the path/filepath package. The name of the extracted file is then displayed on the console using fmt package.
Syntax
filepath.Rel
This function is used to find the relative path between two file paths. It takes two inputs- the basepath and the targetpath.
Algorithm
Step 1 − Create a package main and declare fmt(format package), path/filepath package in the program where main produces executable codes and fmt helps in formatting input and output.
Step 2 − Create a function main and in that function create two path variables path1 and path and assign them absolute path.
Step 3 − Now use filepath.Rel function to get the relative path from the two absolute paths.
Step 4 − If the path is obtained successfully, its printed on the console but when it’s not obtained successfully print the error on the console and return.
Step 5 − The print statement is executed using fmt.Println() function
Example
In this example, we will use filepath.Rel function to get the relative path from two absolute paths. Let’s have a look at the code.
package main import ( "fmt" "path/filepath" ) func main() { Path1 := "/home/asus/user/src/github.com/folder1" //absolute path1 Path2 := "/home/asus/user/src/github.com/folder2" //absolute path2 relPath, err := filepath.Rel(Path1, Path2) //use the Rel function to get the relative path if err != nil { fmt.Println("Error:", err) //print error if no path is obtained return } fmt.Println("Relative path:", relPath) //print the relative path }
Output
Relative path: ../folder2
Method 2: Using Strings Package
In this method, the absolute paths are first divided into their component parts using the strings.Split function. In the next step components are iterated and compared to find the common prefix between the two pathways. An error is returned if there is no common prefix between the paths. Otherwise, the remaining components in Path1 are added first, followed by the remaining components in Path2, to create the relative path.
Syntax
func Split(str, sep string) []string
Split() function is used to split a string through a provided separator. This function is present in strings package and it accepts the string to split as an argument along with a separator. The function then returns the final array of strings as a result.
func len(v Type) int
The len() function is used to get the length of any parameter. It takes one parameter as the data type variable whose length we wish to find and returns the integer value which is the length of the variable.
Algorithm
Step 1 − Create a package main and declare fmt(format package), strings package in the program where main produces executable codes and fmt helps in formatting input and output.
Step 2 − Create a function relativePath with two absolute paths defined in main function and an error of string type.
Step 3 − In this step, split the paths into components using strings.Split function.
Step 4 − Then, iterate the components1 and components2 to check if they have any common prefix or they are equal.
Step 5 − If the paths do not have a common prefix, print it on the console.
Step 6 − Then, Build a relative path by adding ../ in the remaining components of the absolute path.
Step 7 − After all the previous steps performed return the relative path to the function.
Step 8 − In the main if the relative path is obtained successfully, it will be printed on the console but if an error occurs while obtaining the path, print the error and return.
Step 9 − The print statement is executed using fmt.Println() function
Example
In this example, we will use strings.Split function to split the paths into components and build relative paths.
package main import ( "fmt" "strings" ) func relativePath(Path1, Path2 string) (string, error) { components1 := strings.Split(Path1, "/") //break the path into components components2 := strings.Split(Path2, "/") var i int for i = 0; i < len(components1) && i < len(components2); i++ { if components1[i] != components2[i] { //check if they are equal break } } if i == 0 { return "", fmt.Errorf("Paths do not have a common prefix") //print error if thry don’t have a common prefix } var relativePath string for j := i; j < len(components1)-1; j++ { relativePath += "../" //append the directory into remaining components } for j := i; j < len(components2); j++ { relativePath += components2[j] + "/" } return relativePath, nil //return the relativepath } func main() { Path1 := "/home/user/go/src/github.com/project/folder1" //absolute path1 Path2 := "/home/user/go/src/github.com/project/folder2" //absolute path2 relPath, err := relativePath(Path1, Path2) if err != nil { fmt.Println("Error:", err) //if no path is obtained print error return } fmt.Println("Relative path:", relPath) //print the relativepath }
Output
Relative path: folder2/
Conclusion
We executed the program of getting a relative path from two absolute paths using two examples. In the first example we used filepath.Rel to find the relative path and in the second example we used strings package functions.
- Related Articles
- C# Program to Get the relative path from two absolute paths
- Golang program to get the name of the file from the absolute path
- Get an Absolute Filename Path from a Relative Filename Path in Java
- Get an Absolute Filename Path from a Relative Filename with Path in Java
- C# Program to get the name of the file from the absolute path
- Java Program to get the File object with the absolute path for the directory or file
- Get Absolute path of a file in Java
- How to get the absolute path of a file using tkFileDialog(Tkinter)?
- Get the absolute path for the directory or file in Java
- Golang Program to get a substring from the string
- Golang program to find all paths in a graph
- Golang Program To Get The Last Item From The Array
- Golang Program To Get The First Item From The Array
- CSS Absolute and Relative Units
- Golang Program to get the denominator from a rational number
