Cross Platform File Paths

· 170 words · 1 minute read

Unlike with URLs which have a standardised format (they use forward-slashes to separate folders), file path separators will differ between operating systems. This is mainly a historic issue, as it’s almost inconceivable to change them at this stage. This means Windows uses back-slashes and *nix systems use forward slashes.

This is a pain however when writing cross platform software because if you know a file exists in a folder, and want to get it’s contents, you will have to use it’s folder name, a slash separator and the file name. We can tackle this problem in a number of ways. Here are two quick ones:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
package main

import (
	"fmt"
	"os"
	"path/filepath"
)

func main() {

	// Make a cross-platform file
	// unix='dir/example' windows='dir\example'

	// Option 1
	examplePath1 := "dir" + string(os.PathSeparator) + "example"
	fmt.Println("PathSeparator: " + examplePath1)

	// Option 2
	examplePath2 := filepath.FromSlash("dir/example")
	fmt.Println("FromSlash: " + examplePath2)
}

read a csv file into a struct

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!