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.