Accesing files using os.open

Hi,
I’m beginner to GOlang and trying to understand what is wrong in the below code, or how to go about fixing it ?

Machine: Windows
IDE : Eclipse

main.go

This file has a call to the package ‘fileOp.go’ for reading a text file
fileOp.OpenReadFile("abc.txt")

fileOp.go

func OpenReadFile(fp string){
file,err:= os.Open(fp)
fmt.Println("file is :",file)
fmt.Println("File open error:",err)
}

My question is where should this file ‘abc.txt’ be located ? I tried placing the file in the package dir and also inside where the main.go is, but both the cases print the below

file is :
File open error: open abc.txt: The system cannot find the file specified.

So what is the default path structure where a os.Open would look for files.
Also if a relative path is specified say like os.Open("D:\MyGo\abc.txt") i end up seeing an error like below

unknown escape sequence

which i tried changing to ‘D:/\MyGo/\abc.txt’ but didn’t help. i got the same error back.

Any help would be appreciated.

Thanks
AK

When you specify a relative path it will be resolved relative to your current working dir.

How you can set/change/find out in eclipse I can’t say, since I prefer to use the shell directly.

In a literal string, a backslash introduces an escape sequence, like, for example, \n for “newline”.

To get a plain backslash as a result, double the backslash in the literal string:

os.Open("D:\\MyGo\\abc.txt")
3 Likes

This did work and the file is opened. Thanks christophberger

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