Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Porting from Glib to Qt

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?

like image 515
Seb Avatar asked Oct 23 '25 11:10

Seb


1 Answers

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"
like image 149
lpapp Avatar answered Oct 26 '25 02:10

lpapp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!