Home > Back-end >  Unable to create folder on Windows
Unable to create folder on Windows

Time:06-11

I'm trying to create a folder on Windows but keep getting an error and do not understand why.

The code snippet:

reader := bufio.NewReader(os.Stdin)
fmt.Print("Hostname: ")
hostname, _ := reader.ReadString('\n')

now := time.Now().Format("20060102150405")
var folderName string = fmt.Sprintf("%s_%s", now, hostname)

err := os.Mkdir(folderName, os.ModePerm)

if err != nil {
    log.Fatal(err)
}

The error (translated from Dutch):

2022/06/10 13:37:13 mkdir 20220610133713_TEST
: The syntax of the file name, folder name or volume name is incorrect.
exit status 1

I tried using the full path with \\ and a relative path .\ or .\\

I got around the error with the code below, but that's not the way to go... ;)

cmd := exec.Command("cmd.exe", "/C", fmt.Sprintf("mkdir %s", folderName))
err := cmd.Run()

The issues is probably obvious but I fail to see the reason. Maybe something Windows specific?

Anyway thanks for having a look.

CodePudding user response:

Reader.ReadString() documents that:

ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter.

Reader.ReadString('\n') does not trim the newline character, the returned string will contain a trailing \n character.

You can see it if you print it like this:

fmt.Printf("%q\n", folderName)

This will output (try it on the Go Playground):

"20091110230000_TEST\n"

And Windows does not allow the newline character in folder names.

Solution: use bufio.Scanner.

For example:

scanner := bufio.NewScanner(strings.NewReader("TEST\n"))
if !scanner.Scan() {
    return // No input
}
hostname := scanner.Text()

now := time.Now().Format("20060102150405")
var folderName string = fmt.Sprintf("%s_%s", now, hostname)

fmt.Printf("%q\n", folderName)

This will output (try it on the Go Playground):

"20091110230000_TEST"
  • Related