Search code examples
c++linuxqtsystemqstring

Use system() with a variable in Qt


I want to run a system command in Qt such as:

system("echo 50 > //sys//class//pwm-sunxi//pwm0//duty_percent")

Now the problem is, I want to use a variable for the 50 from the code above so that I can use a slider to change the values

if it any helps, I am running Linux Debian distro on a Cubieboard A20

I've tried using

system("echo "INTtoString(variable)" > //sys//class//pwm-sunxi//pwm0//duty_percent")

but it shows the error

expected ) before INTtoString

Any ideas?


Solution

  • First and foremost, I would use QFile for this writing operation.

    If you really wish to stick with the current concept, I would personally use two things:

    1. QString's arg() method to create the string.

    2. qPrintable(myQString) to get the const char* back for the execution.

    So, I would be writing something like this:

    QString myString = QString("echo %1 > /sys/class/pwm-sunxi/pwm0/duty_percent").arg(INTtoString(variable));
    system(qPrintable(myString));
    

    But really, here is a much better approach:

    QFile file("/sys/class/pwm-sunxi/pwm0/duty_percent");
    if (file.open(QIODevice::WriteOnly | QIODevice::Text
                  | QIODevice::Truncate | QIODevice::Unbuffered))
        if (file.write(INTtoString(variable)) != 2)
            qDebug() << "Failed to write all:" << file.errorString();
    else
        qDebug() << "Failed to open:" << file.errorString();
    // No need to close as it will be done automatically by the RAII feature
    

    Please also note that the double forward slashes are superfluous, then.