c++ - 如何使用 QProcess 从特定文件夹执行类似 "qmake -v > 1.txt"的命令?

标签 c++ qt qprocess qtcore qfile

我有一个文件夹的路径和一个从该文件夹执行的命令。这是一个任意的复杂命令。例如:qmake -v > 1.txt .

我想我需要运行一个 shell(cmd.exe,因为我在 Windows atm 上。),并在那里执行命令:

QProcess::startDetached("cmd.exe", QString("qmake -v > 1.txt").split(' ', 

QString::SkipEmptyParts), "C:/文件夹/");

但它不起作用。它会在指定路径启动控制台窗口 (cmd.exe),但不会执行命令。然后我试过了:

QProcess::startDetached("cmd.exe", QStringList() << "start" << QString("qmake -v > 1.txt").split(' ', QString::SkipEmptyParts), "C:/folder/");

也没有运气。最后,只是为了测试我是否可以使用它:

QProcess::startDetached("qmake.exe", QString("-r -tp vc").split(' ', QString::SkipEmptyParts), "C:/folder_containing_qt_project/");

控制台窗口会短暂出现,但不会生成项目。

我做错了什么,我怎样才能用 QProcess 实现我想要的? (如果没有其他方法,我不介意使用 WinAPI,但强烈希望在 Linux/Mac OS X/Windows 上使用相同的代码)?

可能值得注意的是,在同一应用程序的另一种方法中,我可以毫无问题地执行 notepad.exe <path to a text file>startDetached .

最佳答案

我认为您正在寻找这种方法:

void QProcess::setStandardOutputFile(const QString & fileName, OpenMode mode = Truncate)

你会像这样使用它:

QProcess myProcess;
myProcess.setStandardOutputFile("1.txt");
myProcess.start("qmake -v");
myProcess.waitForFinished();

您还可以将输出读入应用程序并使用 QFile 将其写出。这可能会让您朝那个方向前进:

QByteArray QProcess::readAllStandardOutput()

Regardless of the current read channel, this function returns all data available from the standard output of the process as a QByteArray.

因此,您可以这样写,但它有点复杂,并且可能会占用大量内存,因此它仅用于演示目的,没有 block 读写。

QProcess myProcess;
myProcess.start("qmake -v");
myProcess.waitForFinished();
QFile file("1.txt");
file.open(QIODevice::WriteOnly);
file.write(myProcess.readAllStandardOutput());
file.close();

免责声明:为了简单起见,我有意没有编写错误检查。

关于c++ - 如何使用 QProcess 从特定文件夹执行类似 "qmake -v > 1.txt"的命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23436138/

相关文章:

c++ - 使用字符指针测试条件

c++ - 编辑其他进程内存

c++ - 如何在 VC10 中跨 DLL 边界使用具有静态数据成员的模板化类

c++ - 即使文件存在,如何修复 QFile 打开错误(未知错误)?

c++ - Q进程: Reset working directory during runtime

c++ - 将 QProcess 输出读取到字符串

c# - 总是从串口得到 254

c++ - Windows 7 上的奇怪行为 QT QSerialPort 不会更改串行 com 端口的设置

c++ - 如何找到包含标题的位置