How to get absolute path of file or directory, that does *not* exist?

眉间皱痕 提交于 2019-11-28 02:44:38

问题


How can I determine the absolute path of a file or directory from a given relative path in C/C++ on GNU/Linux?
I know about realpath(), but it does not work on non-existing files.

Let's say the user enters ../non-existant-directory/file.txt, and the programs working directory is /home/user/.
What I need is a function that returns /home/non-existant-directory/file.txt.

I need this function to check if a given path is in a certain subdirectory or not.


回答1:


Try realpath. If it fails, start removing path components from the end one at a time and retrying realpath until it succeeds. Then append the components you removed back onto the result of the successful realpath call.

If you're sure the containing directory exists and you just want to make a file there, you only have to remove at most one component.

Another approach would be to just create the file first, then call realpath.



来源:https://stackoverflow.com/questions/11034002/how-to-get-absolute-path-of-file-or-directory-that-does-not-exist

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