How to get the correct path example?

I have a slight problem with itching. How to get the right example for the Windows path in Qt?

Say I have a path c:\documents and settings\wolfgang\documents stored in QString str , and I want to know the correct case, here is C:\Document and Settings\Wolfgang\Documents . QDir(str).absolutePath() does not give me the path with the correct case.

Any suggestions since I don't know what else could I try?

Thank you for your time!

+9
c ++ qt
source share
3 answers

There is no easy way to do this, but you can try to do a QDir.entryList and then make case insensitive to search by results. This will give you the correct file name. Then you need to get absolutePath for this result.

This should provide a saved file for the path / file name.

+5
source share

I think that the decision currently made by the OP, listing all the children at each level of the path directory, is really inefficient, fast, and dirty. There must be a better way. Since this problem with a path with the correct case applies only to Windows (other platforms are case sensitive, AFAIK), I think it’s perfectly correct to use #ifdef and call the Windows API and write something like this:

 #if defined(Q_OS_WIN32) #include <Windows.h> // Returns case-correct absolute path. The path must exist. // If it does not exist, returns empty string. QString getCaseCorrectPath(QString path) { if (path.isEmpty()) return QString(); // clean-up the path path = QFileInfo(path).canonicalFilePath(); // get individual parts of the path QStringList parts = path.split('/'); if (parts.isEmpty()) return QString(); // we start with the drive path QString correctPath = parts.takeFirst().toUpper() + '\\'; // now we incrementally add parts one by one for (const QString &part : qAsConst(parts)) { QString tempPath = correctPath + '\\' + part; WIN32_FIND_DATA data = {}; HANDLE sh = FindFirstFile(LPCWSTR(tempPath.utf16()), &data); if (sh == INVALID_HANDLE_VALUE) return QString(); FindClose(sh); // add the correct name correctPath += QString::fromWCharArray(data.cFileName); } return correctPath; } #endif 

I have not tested this, there may be some minor issues. Please let me know if this does not work.

0
source share

You can use QFileInfo for this, and the function

QString QFileInfo::absoluteFilePath () const will return the absolute path to the file.

eg:

 QFileInfo yourFileInfo(yourPath); QString correctedCasePath = yourFileInfo.absoluteFilePath (); 

Another advantage is that yourPath can be a QFile or QString so that you can use it directly with the handle you have. In addition, there are other operations using QFileInfo that can get useful information about the referenced file.

Hope this helps.

-one
source share

All Articles