system() library function is not writing output in a text file
-
Hi All,
I am writing an application that will be used to set the selected WIFI network. The user will enter SSID and its password and on a button click, I am calling a function that will take these 2 parameters. The code snippet for this function is as follows:
QString strCmdWifi = "nmcli dev wifi connect '"+ssid+"' password '"+pwd+"' &> out.txt"; qDebug() << "strCmdWifi" << strCmdWifi; // Prints correct command int nCmdResponse = system(strCmdWifi.toStdString().c_str()); if(nCmdResponse == 0) { QFile file("out.txt"); if(file.open(QIODevice::ReadOnly | QIODevice::Text)) { QString strVal(file.readAll()); qDebug() << "strVal" << strVal; // Prints blank file.close(); if(strVal.startsWith("Error",Qt::CaseInsensitive) || strVal.contains("Error",Qt::CaseInsensitive)) { // Handling error here. } else { // Showing successful msg } } }
"ssid" and "pwd" are parameters. I am not getting any error in the out.txt file if I pass the wrong "pwd" value. The application is running with sudo permission. If I run the command ( strCmdWifi variable) on a terminal, it writes an error in a file but when I am trying from the Qt application, it is not writing an error in the file.
-
@Himanshu-Rohilla
This seems to be a question aboutsystem()
and maybenmcli
, not about Qt.Verify that the redirection works in a much simpler command, e.g.
ls -l &> out.txt
. Verify some other command which produces an error message (ls -abcdefghijklm &> out.txt
) sends it to the file too. -
You are using a relative path the the output file. Verify that the current working directory is where you think it is if you are looking for the file manually.
The error message when you provide an invalid password is almost certainly written to
stderr
. You are using abash
redirection&>
to attempt capturing bothstdout
andstderr
.system()
runs the command withsh
which may not support that syntax.You do not need the temporary file at all if you use QProcess.
Your method is fragile. Think what occurs if the password provided by the user contains a single quote (or something more deliberately structured to be malicious).
-
@ChrisW67 said in system() library function is not writing output in a text file:
system()
runs the command withsh
which may not support that syntaxOn Ubuntu at least
/bin/sh
is a link to/bin/bash
. But we shall see if the OP tries e.g. thels -l &> out.txt
. -
system() is the naive OS interface mecahnism. It will stall the calling program while executing. an async QProcess is a better mechanism if you must call a subshell...The sophisitcated Linux way is to use the dbus system to talk directly to NetworkManager.