filepath.Join removes dot

喜你入骨 提交于 2020-01-06 04:54:08

问题


i have a problem with create path for rsync.

x := filepath.Join("home", "my_name", "need_folder", ".")
fmt.Println(x)

I get "home/my_name/need_folder", but need "home/my_name/need_folder/.", how fix without concat? In linux folder with name "." not impossible.

Thank you!


回答1:


You can't do that with the filepath.Join() as its documentation states:

Join calls Clean on the result...

And since . denotes the "current" directory, it will be removed by filepath.Clean():

It applies the following rules iteratively until no further processing can be done:

  1. [...]

  2. Eliminate each . path name element (the current directory).

And in fact you can't do what you want with the path/filepath package at all, there is no support for this operation.

You need to use string concatenation manually. Use filepath.Separator for it, it'll be safe:

x := filepath.Join("home", "my_name", "need_folder") +
    string(filepath.Separator) + "."
fmt.Println(x)

Output (try it on the Go Playground):

home/my_name/need_folder/.



回答2:


When you invoke filepath.Join it actually has two steps

  1. concat the path with separator, by this step actually you will get "home/my_name/need_folder/."
  2. clean the path, which will do a lexical processing on the path and return the shortest path name equal to the path you get in step 1.

In step 2, if you read the source code you will find, it invokes a Clean function and the function will

Eliminate each . path name element (the current directory).

And you can try:

x := filepath.Join("home", "my_name", "need_folder", ".", "." , ".") fmt.Println(x)

you will still get the same result.

If suggest you use concat in this case :)



来源:https://stackoverflow.com/questions/51669486/filepath-join-removes-dot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!