I need a similar to .NET method for safely combining path parts without worrying for platform specifics of the path separator.
Is there such class and method in QT4?
Something like:
QPath::Combine
I need a similar to .NET method for safely combining path parts without worrying for platform specifics of the path separator.
Is there such class and method in QT4?
Something like:
QPath::Combine
You may use the static methods
QDir::fromNativeSeparators
andQDir::toNativeSeparators
and then use/
everywhere when manipulating the path.There is not any function that can be used as direct replacement for
Path.Combine()
so you have to write it by your own.You may do it in the hard way (handling everything by yourself) or simply use
QDir::cleanPath()
:I used
QDir::separator()
but as pointed out in Cross-platform way of constructing a FS path with Qt you do not really need it and you simply can use the /.QDir::cleanPath()
will remove double / (or double \, according toQDir::separator()
) and will resolve . and .. to appropriate values. See also Qt equivalent of PathAppend? for code about QTPathAppend()
replacement.As said it mimics
PathAppend()
native function (see MSDN) but this is not an exact replacement ofPath.Combine()
becausePath.Combine()
doesn't perform an cleaning or normalization (it just appends strings, handling directory separators in the proper way, see MSDN). If you need an exact replacement you may use this one:This function will not add a trailing directory separator if
path2
is a directory name (it doesn't perform any check and path may even not exist at all). Also note thatpath2
must be a sub-path ofpath1
(relative paths upper thanpath1
aren't supported, if you need them you have to use previous version withQDir::cleanPath()
), also ifpath2
is rooted thenpath2
is returned (this implementation is pretty naive, for example it doesn't detectc:\directory
as a rooted path).trim()
andtrimEnd()
functions remove trailing directory separator (for a possible, generic, implementation see How do I remove trailing whitespace from a QString? as starting point). Algorithm to ensure there is a trailing directory separator is same one described in How to ensure there is trailing directory separator in paths? (simplified because here we always have one directory separator given byQDir::separator()
).I don't know of anything exactly like that, but you can get close by using
QDir::cd()
:Unfortunately, I think that only works for directories, not files. For files, you could use
QDir::filePath()
: