如何将参数传递给带引号的系统函数?

how can I pass a parameter to the system function with quotes?

我正在尝试减少顶级函数的列并将其保存到文件中,但我不知道如何使用带引号的 system() 函数来实现。我是这样做的:

system("top -b n1 | grep \"^ \" | awk '{ printf(\"%s %s %s %s %s %s %s\n\", , , , , , , ); }' >> file

我很确定问题出在引号上,有人可以帮我吗?

问题不在于你的报价。首先,您缺少结束符 "),而且我不确定您是如何尝试使用变量 file,但看起来您将字符串与变量混淆了。确保在将变量 file 添加到命令字符串时确实将其用作变量。最后,您正在转义 \n 错误,这会扰乱您的输出。您应该转义该反斜杠,因此您需要在 awk 命令中输入 \n\n 结束。

这应该有效:

string file = "test.txt"; 
system((string("top -b n1 | grep \"^ \" | awk '{ printf(\"%s  %s  %s  %s  %s  %s  %s\n\", , , , , , , ); }' >> ") + file).c_str());