Porting from Glib to Qt

1.4k Views Asked by At

I am porting an application from Glib to Qt.

I do have a lot of API specific to Gtk, but it's difficult to find the equivalent variants in Qt. I am looking for the alternative of these:

  • g_path_get_basename
  • g_path_get_dirname
  • strdup

Any idea?

2

There are 2 best solutions below

0
On BEST ANSWER

There really are not direct equivalences for these, but this is the closest that you get:

g_path_get_basename

QString QFileInfo::fileName() const

Returns the name of the file, excluding the path.

Note: do not get tempted by the similarly 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 way for empty file names or those which end with a slash.

g_path_get_dirname

QString QFileInfo::path() const

Returns the file's path. This doesn't include the file name.

Note that, if this QFileInfo object is given a path ending in a slash, the name of the file 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. Do not get tempted that QString would be the same. It simply is not because that would have the UTF overhead, too, among other things.

Here is some code to print these out:

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"
1
On

You can use QFileInfo for the following:

g_path_get_basename => QFileInfo::baseName or QFileInfo::completeBaseName

g_path_get_dirname => QFileInfo::path

strdup is not needed. Simply use QString allocated on the stack in most cases. Qt API take QString.