5

How can I use the system command where the command is written in a QString?

Like:

QString command="chmod -R 777 /opt/QT/examples/code/TestGUI/Data";    
system(command);

While compiling, I get this error:

cannot convert ‘QString’ to ‘const char*’
  for argument ‘1’ to ‘int system(const char*)’

Can anyone suggest something?

Mat
  • 202,337
  • 40
  • 393
  • 406
harnek singh
  • 51
  • 1
  • 1
  • 2
  • 1
    possible duplicate of [QString to char conversion](http://stackoverflow.com/questions/2523765/qstring-to-char-conversion) – Mat May 29 '12 at 12:16

6 Answers6

12

Use the qPrintable() macro

system(qPrintable(command));

Vinicius Kamakura
  • 7,665
  • 1
  • 29
  • 43
8

You need get the raw character array from the QString. Here is one way:

system(command.toStdString().c_str());
Jason B
  • 12,835
  • 2
  • 41
  • 43
7

Ankur Gupta wrote, use QProcess static function (link to description):

int QProcess::execute ( const QString & program )

In your situation:

QProcess::execute ("chmod -R 777 /opt/QT/examples/code/TestGUI/Data");
Christophe Weis
  • 2,518
  • 4
  • 28
  • 32
firescreamer
  • 620
  • 8
  • 20
6

QProcess class http://doc.qt.io/qt-5/qprocess.html. It's what you need.

Christophe Weis
  • 2,518
  • 4
  • 28
  • 32
Ankur Gupta
  • 2,284
  • 4
  • 27
  • 40
0

To change permission you could use setPermissions of QFile

Vlad Gordin
  • 109
  • 4
0

you can convert QString to const char*.

if your string is in UTF8, then you can use:

const char* my_command = command.toUtf8().constData() ;
system(my_command);

else if your string is not in UTF8, then you can use:

command.toLatin1().constData() ;
system(my_command);

in this case second one is what you want.

AliS
  • 111
  • 2
  • 9
  • I kno0w this post is ancient , but QProcess::execute ("service bluetooth status"); "forwards results to calling process" -- HOW to write a C++ code to accomplish such "forwarding"? –  Jan 19 '23 at 15:54