Resolving a relative path without referencing the current directory on Windows

强颜欢笑 提交于 2019-12-10 09:19:05

问题


I have a windows cpp app and I want to resolve paths relative to a specific directory without changing the current directory. This means I can't use GetFullPathName since it resolves paths relative to the current directory. Since this is a security sensitive issue I would rather not roll my own but use a sanctioned API.

I looked around for a good answer, but couldn't find anything. Surely this is a common issue for web servers or multithreaded environments. How do other people do this? Any help would be greatly appreciated.

For instance: You run your app from C:\appfolder\exes\myapp.exe while the data is in C:\appfolder\data. I want to resolve sillyfolder\..\mydata.txt to C:\appfolder\data\mydata.txt.


回答1:


The standard (C++ or Win32) libraries do not do this for you, it seems. But making a relative path is a good exercise. Here are a few useful links to see how to start (treat scripts as pseudocode):

  • Converting an absolute path to a relative path
  • Windows CMD: Get relative path from absolute path
  • MakeRelative - makes a file name relative to a base path

Converting an absolute pathname to relative requires

  • the given target path which should be converted
  • a path which is the current directory.

The conversion would be done as a string-manipulation:

  • start by finding the longest common prefix which ends with a path-separator.
  • if there is no common prefix, you are done
  • strip the common prefix from (a copy of...) the current and target strings
  • replace each directory-name in the current string with ".."
  • add that (with a path-separator) in front of the target string
  • return that combined string

Unlike Unix pathnames (aside from the sense of "/" versus "\" for separators), Windows pathnames have additional complications:

  • within the same machine, they can have device names (a letter followed by a ":")
  • UNC pathnames, which begin with "\".

For the latter case (UNC paths), if the current and target paths are not on the same host, then relative paths are meaningless. However, device names and pathnames are not that tightly bound together (note that Windows added the ability to change devices with chdir later, as an option), and depending on the application one could make relative pathnames between devices by considering only the path part.



来源:https://stackoverflow.com/questions/28952366/resolving-a-relative-path-without-referencing-the-current-directory-on-windows

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