如何获得文件或目录的绝对路径,这并*不*存在? [英] How to get absolute path of file or directory, that does *not* exist?

查看:138
本文介绍了如何获得文件或目录的绝对路径,这并*不*存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何确定在C / C ++的GNU / Linux的一个给定的相对路径的文件或目录的绝对路径?结果
我知道的真实路径(),但它并没有对不存在的文件。

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.

假设用户输入 ../不存在的目录/ file.txt的和程序工作目录 / home / user的/ 。结果
我需要的是一个返回 /home/non-existant-directory/file.txt

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.

推荐答案

尝试的真实路径。如果失败了,启动的时间和重试的真实路径,直到它成功从末尾一个中卸下路径组件。然后附加您删除放回成功的的真实路径调用的结果的组件。

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.

这篇关于如何获得文件或目录的绝对路径,这并*不*存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆