Porting from Glib to Qt
There really are no direct equivalents for them, but this is the closest you get:
g_path_get_basename
QString QFileInfo :: fileName () const
Returns the name of the file excluding the path.
Note. Don't fall for the interlocutor with the so called baseName () and completeBaseName () in Qt as they are not the same. The Qt and Glib developers decided to use different terms for the same things.
Also, even this is not the same, because it will not behave the same for empty filenames or for those ending with a slash.
g_path_get_dirname
QString QFileInfo :: path () const
Returns the path to the file. This does not include the filename.
Note that if this QFileInfo object is given a path that ends with a slash, the filename is considered empty and this function will return the entire path.
Note: absolutePath () or canonicalPath () will not work because they will return absolute paths, whereas the glib variant returns relative paths.
strdup
Just use std::string
, std::array
or QByteArray
. Don't be tempted to QString
be the same. It's just not because it would have UTF overhead too.
Here's the code to output:
main.cpp
#include <QFileInfo>
#include <QDebug>
#include <QByteArray>
#include <iostream>
#include <glib.h>
using namespace std;
int main()
{
const char filePath[] = "tmp/foo.bar.baz";
qDebug() << "=========== Glib ===============\n";
cout << "Base name: " << g_path_get_basename(filePath) << endl;
cout << "Directory name: " << g_path_get_dirname(filePath) << endl;
cout << "String dup: " << strdup(filePath) << endl;
qDebug() << "\n=========== Qt =================\n";
QFileInfo fileInfo(filePath);
qDebug() << "File name:" << fileInfo.fileName();
qDebug() << "Directory name:" << fileInfo.path();
qDebug() << "String dup:" << QByteArray("foo.bar.baz");
return 0;
}
main.pro
TEMPLATE = app TARGET = main QT = core SOURCES += main.cpp packagesExist(glib-2.0) { CONFIG += link_pkgconfig PKGCONFIG += glib-2.0 }
Build and run
qmake && make && ./main
Output
=========== Glib ===============
Base name: foo.bar.baz
Directory name: tmp
String dup: tmp/foo.bar.baz
=========== Qt =================
File name: "foo.bar.baz"
Directory name: "tmp"
String dup: "foo.bar.baz"
source to share