Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open a file in the same directory as the .go source file in Go

Tags:

go

When in a source file $PWD/dir/src.go I use

os.Open("myfile.txt")

it looks for myfile.txt in $PWD (which looks normal).

Is there way to tell Go to look for myfile.txt in the same directory as src.go ? I need something like __FILE__ in Ruby.

like image 935
Blacksad Avatar asked Feb 20 '23 21:02

Blacksad


1 Answers

Go is not an interpreted language so looking for a file in the same location as the source file doesn't make any sense. The go binary is compiled and the source file doesn't need to be present for the binary to run. Because of that Go doesn't come with an equivalent to FILE. The runtime.Caller function returns the file name at the time the binary was compiled.

I think perhaps if we understood why you actually wanted this functionality we could advise you better.

like image 134
Jeremy Wall Avatar answered Feb 26 '23 20:02

Jeremy Wall