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
+5k Golang : Perform sanity checks on filename example
+2k Python : Find out the variable type and determine the type with simple test
+2.1k Linux/Unix/PHP : Restart PHP-FPM
+6.6k Golang : calculate elapsed run time
947 Golang : How to pass data between controllers with JSON Web Token
+2.7k Golang : What is StructTag and how to get StructTag's value?
+16.4k Golang : Saving(serializing) and reading file with GOB
+1.1k Golang : How to extract video or image files from html source code
+11.6k Golang : Convert(cast) string to uint8 type and back to string
+12.1k Golang : How to read JPG(JPEG), GIF and PNG files ?
+2.3k CodeIgniter/PHP : Remove empty lines above RSS or ATOM xml tag
+5.4k Golang : Increment string example