Golang : File path independent of Operating System
There are times a program need to determine the operating system it is running on and construct a proper file path for file I/O.
Go has the http://golang.org/pkg/path/filepath/ package that will handle the cross plat form / operating system
Just use string(filepath.Separator)
through out your code will do.
Below is the an example code in Go:
package main
import (
"fmt"
"runtime"
"path/filepath"
)
func main() {
detect := "This OS is " + runtime.GOOS + " type and use "+ string(filepath.Separator) + " as file separator"
fmt.Println(detect)
}
The output will be
Unix/Linux
:
This OS is linux type and use / as file separator
Windows
:
This OS is windows type and use \ as file separator
See also : Golang : Detect (OS) Operating System
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+8.1k Prevent Write failed: Broken pipe problem during ssh session with screen command
+11.5k Golang : Concurrency and goroutine example
+25.1k Golang : Generate MD5 checksum of a file
+11.3k Golang : Format numbers to nearest thousands such as kilos millions billions and trillions
+11.4k Golang : Fuzzy string search or approximate string matching example
+13.5k Golang : Image to ASCII art example
+43.1k Golang : Get hardware information such as disk, memory and CPU usage
+9.4k Golang : Read file with ioutil
+15.1k Golang : Get timezone offset from date or timestamp
+11.5k Golang : Calculations using complex numbers example
+11.2k Use systeminfo to find out installed Windows Hotfix(s) or updates
+6.9k Javascript : How to get JSON data from another website with JQuery or Ajax ?