Kevin E
Kevin E

Reputation: 13

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?

Upvotes: 1

Views: 1640

Answers (3)

László Papp
László Papp

Reputation: 53215

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.

Upvotes: 4

Silas Parker
Silas Parker

Reputation: 8157

To avoid the shell call, just use a QFile:

void change_duty_percent(int value)
{
  QFile duty_pc("/sys/class/pwm-sunxi/pwm0/duty_percent");
  duty_pc.open(QIODevice::WriteOnly | QIODevice::Truncate);
  duty_pc.write(QString::number(value));
  duty_pc.close();
}

If you do want to use the shell, make sure you convert to a char* correctly by using a separate instance of QByteArray:

QString command = QString("echo %1 > /sys/class/pwm-sunxi/pwm0/duty_percent").arg(value);
QByteArray commandBA(command.toLocal8Bit());
system(commandBA.data());

Upvotes: 2

ratchet freak
ratchet freak

Reputation: 48216

create a QString to hold the command:

QString command = QString("echo %1 > //sys//class//pwm-sunxi//pwm0//duty_percent");

then you can use arg to replace %1 with another value:

system(command.arg(50).toLocal8Bit().constData());

Upvotes: 1

Related Questions