I'm new to Go, I want to do a simple program that reads filename from user and display it's contents back to user. This is what I have so far:

fname := “D:\myfolder\file.txt”

f, err := os.Open(fname)
if err != nil {
fmt.Println(err)
}

var buff []byte
defer f.Close()
buff = make([]byte, 1024)
for {
n, err := f.Read(buff)

if n > 0 {
    fmt.Println(string(buff[:n]))
}
if err == io.EOF {
    break
}

}

error : The filename, directory name, or volume label syntax is incorrect.

Your problem is probably that backslashes in normal strings are escape sequences. There are raw strings delimited by backticks that are easier to use with backslashes. The following string constants are equal:

"D:\\myfolder\\file.txt"
`D:\myfolder\file.txt`

while "D:\myfolder\file.txt" contains the escape sequences \m and \f, where I’m not sure if any of them mean anything useful but they might mean something, leaving you with control characters in the file name. Even if they aren’t parsed as control sequences they might get parsed to themselves, \m meaning a literal m and leaving your path entirely without slashes.

I tried double slash option , not working same error , infact I am accepting the path from user .

Show your code and we can take a look.

package main

import (
“fmt”
“bufio”
“os”
“io”

)

func main(){
fmt.Println("Enter path : ")
dirpath := bufio.NewReader(os.Stdin)
actualpath, _ := dirpath.ReadString(’\n’)
f, err := os.Open(actualpath)
if err !=nil{
fmt.Println(err)
}

var buff []byte
defer f.Close()
buff = make([]byte,1024)

for {
n , err := f.Read(buff)

if n > 0{
	fmt.Println(string(buff[:n]))
}
if err == io.EOF{
	break
}
}

}

This gives you a string with a newline at the end, which is not valid for the file name. You can strip the newline or use a bufio.Scanner. (And please try to use the code formatting function in the forum when pasting code, it makes it easier to read and copy/paste.)

Golang uses forward slashes when using paths. ‘/’ that. So if your taking the path in from the user make sure to replace all backward slashes with forward ones

Go is perfectly fine with backslashes as path separators on Windows, although Windows is also fine with forward slashes. If you do need to convert at some point, filepath.ToSlash and filepath.FromSlash will do the right thing for the platform you’re on.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.