如何在QT中获取文件的相对路径 [英] How to get the relative path of the file in QT

查看:1899
本文介绍了如何在QT中获取文件的相对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想在我的应用程序中读取文件Logfile_P_1.txt。但我想获取文件LogFile_P_1.txt的完整路径。在QT :: Dir中获取文件相对路径的最佳方法是什么?因为我需要在Linux上测试我的应用程序,有时候在Windows上测试。



这就是我的工作方式

Hi,
I wanted to read the file "Logfile_P_1.txt" in my application.but I want to get the full path of the file"LogFile_P_1.txt". what is the best way to get the relative path of the File in QT::Dir? because I need to test my application on Linux and some time on Windows.

this is how i am doing

QDir dir("../MyProjects/ProjectB");
QString LFName;
LFName= dir.relativeFilePath("/LogFiles/Logfile_P_1.txt");
 QFile logfile(sdir);



但是收到错误。找不到文件


but getting errors."File not found"

QFile logfile(LFName);
if (!logfile.open(QIODevice::ReadOnly | QIODevice::Text))
{
    qDebug()<<"File not found";
       return false;
}
qDebug()<<"File Found";



我的文件(Logfile_P_1.txt)绝对路径是


My file(Logfile_P_1.txt) absolute path is

C:\MyDevelopment\MyProjects\ProjectB\LogFiles\Logfile_P_1.txt

推荐答案

这是一条相对路径:

This is a relative path:
QDir dir("../MyProjects/ProjectB");



如果当前工作目录不是C:\的子目录MyDevelopment \,路径可能无效(不存在)。



这将返回相对于上述目录的传递名称的路径。


If the current working directory is not a sub directory of "C:\MyDevelopment\", the path will be probably invalid (not existing).

This will return the path to the passed name relative to the above directory.

LFName= dir.relativeFilePath("/LogFiles/Logfile_P_1.txt");



这里有两个问题:


There are two problems here:



  1. 传递的名称以斜杠开头。所以这不是解释为子路径,而是作为绝对路径,返回的路径可能是../../LogFiles/Logfile_P_1.txt\".
  2. 当省略前导斜杠时,返回值只是传递的名称(LogFiles / Logfile_P_1.txt)



这可能不是你想要的,当初始路径错误时无论如何都不会工作。 />




这类问题的通常解决方案是为注册表中存储的日志文件路径定义应用程序设置(Windows)或配置文件(Linux)。 Qt提供了一个类来存储这样的设置。



初始的pathes应该是特定于应用程序的文件夹(通常是应用程序名称),下面有一个子目录(此处为LogFiles)主目录(Linux)和用户文档文件夹(Windows):


This is probably not what you want and won't work anyway when the initial path is wrong.


The usual solution for these kinds of problems is to define an application setting for the log file path stored in the registry (Windows) or a configuration file (Linux). Qt provides a class to store such settings.

The initial pathes should be application specific folders (usually the application name) with a sub directory (here "LogFiles") below the home directory (Linux) and the user document folder (Windows):

/home/<User Name>/<App Name>/LogFiles
C:\Users\<User Name>\Documents\<App Name>\LogFiles





(可选)提供允许更改默认路径的配置选项。



Optionally provide a configuration option that allows changing the default pathes.


这篇关于如何在QT中获取文件的相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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