C++ 从 Qt 中的文件获取相对路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23998009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:37:04  来源:igfitidea点击:

Get relative path from a file in Qt

c++qtqtcoreqdirqfileinfo

提问by user3627590

I am trying to get the relative path from files that I would like to write. Here a situation:

我试图从我想写的文件中获取相对路径。这里有一个情况:

I save a conf file in D:\confs\conf.txt. I have in my programs some files read from D:\images\image.bmp. In my conf.txtI would like to have ../images/image.bmp.

我在 .conf 文件中保存了一个 conf 文件D:\confs\conf.txt。我的程序中有一些从D:\images\image.bmp. 在我的conf.txt我想拥有../images/image.bmp.

I see some useful classes like QDiror QFileInfobut I don't know what it's the best to use. I tried:

我看到了一些有用的类,例如QDirorQFileInfo但我不知道最好使用什么类。我试过:

QDir dir("D:/confs");
dir.filePath(D:/images/image.bmp) // Just return the absolute path of image.bmp

I read the doc and it says filePathonly work with files in the dir set (here D:\confs) but I wonder if there is a way to indicate to search from a different dir and get his relative path.

我阅读了文档,它说filePath只适用于目录集中的文件(这里D:\confs),但我想知道是否有一种方法可以指示从不同的目录搜索并获取他的相对路径。

采纳答案by lpapp

You are looking for the following method:

您正在寻找以下方法:

QString QDir::relativeFilePath(const QString & fileName) const

Returns the path to fileName relative to the directory.

QString QDir::relativeFilePath(const QString & fileName) const

返回文件名相对于目录的路径。

QDir dir("/home/bob");
QString s;

s = dir.relativeFilePath("images/file.jpg");     // s is "images/file.jpg"
s = dir.relativeFilePath("/home/mary/file.txt"); // s is "../mary/file.txt"

Adapting your code according to the examples above, it will look as follows:

根据上面的示例调整您的代码,它将如下所示:

QDir dir("D:/confs");
dir.relativeFilePath("D:/images/image.bmp") // Just return the absolute path of image.bmp
//           ^                   ^

Overall, what you do might be a bad idea since it will couple the config and image paths together. I.e. if you move either of them, the application stops working.

总的来说,你所做的可能是一个坏主意,因为它会将配置和图像路径耦合在一起。即,如果您移动其中任何一个,应用程序将停止工作。

Please also notice the missing quotes.

另请注意缺少的引号。

回答by ch0kee

QDir dir("D:/confs");
dir.relativeFilePath("D:/images/image.bmp");