qt默认路径下面文件无法读取,如何在QT中获取文件的相对路径

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 doingQDir 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()<

return false;

}

qDebug()<

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");

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:

The passed name begins with a slash. So this is not interpreted as sub path but as absolute path and the returned path may be "../../LogFiles/Logfile_P_1.txt".

When omitting the leading slash, the return value is just the passed name ("LogFiles/Logfile_P_1.txt")

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///LogFiles

C:\Users\\Documents\\LogFiles

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值