-5

I'm trying to a read a file (a.go) present in a package into another file (b.go) which is also present in the same package. I used os.Open() method but it is working only when i give the complete system path of the file(ex: home/bin/xyz/a.go).

But, I want the file (a.go) to be read into (b.go) without using the entire system path. Can anyone please help?

Folder

  -- a.go

  -- b.go

//Inside b.go we have a function//

func (xyz){

x:= os.Open("--path to a.go--") // This path shouldn't be the system path

}
Saketh Bv
  • 21
  • 1
  • 7
  • 1
    Relative paths are always resolved to the working directory. Make sure you provide a relative path based on that. See [how to reference a relative file from code and tests](https://stackoverflow.com/questions/31059023/how-to-reference-a-relative-file-from-code-and-tests/31059125#31059125). – icza Jul 02 '19 at 09:54
  • 2
    "But, I want the file (a.go) to be read into (b.go) without using the entire system path." You cannot do this. The running program does not know about your source code. – Volker Jul 02 '19 at 10:07
  • 3
    What makes you think that `a.go` will even be available where the program is executed? – Jonathan Hall Jul 02 '19 at 10:37
  • 4
    This looks like an [XY Problem](http://xyproblem.info/). What are you actually trying to _accomplish_? Explain your goal, and we can help you solve that, rather than this wild goose chase for something you probably shouldn't do. – Jonathan Hall Jul 02 '19 at 10:39

1 Answers1

-4

You can get the path of the current file by using this technique.

_, srcpath, _, _ := runtime.Caller(0)
dirpath := filepath.Dir(srcpath)
err, fp := os.Open(filepath.Join(dirpath, "a.go"))
if err != nil {
     // err
}
...
fp.Close()
Simon Klee
  • 7,097
  • 3
  • 21
  • 11