我需要将一些 linux 命令的输入读取到 QString 变量。首先,我将流重定向到一个临时文件并从中读取。
但是,我不喜欢这种方式。我想避免访问硬盘驱动器,越少越好。
我尝试将环境变量用作“临时文件”,然后使用 getenv
将其放入变量中。
像这样:
QString query="a=$(fdisk -l)";
system(a.toStdString().c_str());
...
char* env;
env= getenv ("a");
然而,我一无所获。将 export
添加到查询中具有相同的结果。
我通过 env
命令手动检查变量。什么都没变!
那么如何解决这个问题呢?有没有更好的方法来做到这一点?
任何想法表示赞赏:)
PS:我也想保留格式,应该保留\t
, \n
...
最佳答案
如果您使用的是 Qt,那么您应该使用 Qt 的方式,利用 QProcess
类。
#include <QProcess>
QString command = "/usr/bin/fdisk";
QStringList arguments;
arguments << "-l";
QProcess process;
process.start(command, arguments);
process.waitForFinished(-1);
QByteArray rawOutput = process.readAllStandardOutput();
QStringList output = QString(rawOutput).split("\n");
foreach (QString line, output)
{
// do something with each line from output
}
关于c++ - 不使用临时文件读取linux命令的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25532120/