使用的是 go mod 跨包调用文件指针出现文件路径问题
文件 Tree:
Gomod
ReadFile
script.go
script_test.go
test.txt
main.go
script.go
var File *os.File
func init(){
Read()
}
func Read(){
p,_:=os.Getwd()
fmt.Println("当前路径是:",p)
file,err:=os.Open("test.txt")
if err!=nil{
log.Fatal(err)
}
File = file
}
script_test.go
file := File
b,err:=ioutil.ReadAll(file)
if err!=nil{
panic(err)
}
defer file.Close()
fmt.Println(string(b))
结果为:
当前路径是: D:\项目文件\GoModLearn\GO 语言编程\调试程序\ReadFile
=== RUN TestRead
helloworld
--- PASS: TestRead (0.00s)
PASS
main.go
func main() {
file:=ReadFile.File
b,err:=ioutil.ReadAll(file)
if err!=nil{
panic(err)
}
defer file.Close()
fmt.Println(string(b))
}
结果为:
当前路径是: D:\项目文件\GoModLearn
2019/12/28 21:48:37 open test.txt: The system cannot find the file specified.
不同的地方调用该文件指针,init()打印的当前路径不一样,求前辈们指导一下~~~