Porting from Glib to Qt

I am migrating an application from Glib to Qt.

I have many APIs specific to Gtk, but it's hard to find equivalent options in Qt. I am looking for an alternative of these:

  • g_path_get_basename
  • g_path_get_dirname
  • strdup

Any idea?

+3


source to share


2 answers


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"

      

+5


source


You can use QFileInfo for the following:

g_path_get_basename

=> QFileInfo::baseName

orQFileInfo::completeBaseName



g_path_get_dirname

=> QFileInfo::path

strdup

not required. Just use the QString

allocated on the stack most of the time. The Qt API accepts QString.

+1


source







All Articles