从 C++ 程序调用 linux 命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5007268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
call linux command from C++ program
提问by jon
I write the following simple c++ program in order to learn about how to call Linux command from C++ program (by using the system command)
我编写了以下简单的 C++ 程序,以了解如何从 C++ 程序调用 Linux 命令(通过使用系统命令)
Please advice why I have the errors from the C++ compiler? what wrong with my program?
请建议为什么我有来自 C++ 编译器的错误?我的程序有什么问题?
more exm2.cc
更多 exm2.cc
#include <stdio.h>
#include <stdlib.h>
int main()
{
system("echo -n '1. Current Directory is '; pwd");
system("mkdir temp");
system();
system();
system("echo -n '3. Current Directory is '; pwd");
return 0;
}
[root@linux /tmp]# g++ -Wall exm2.cc -o exm2.end
/usr/include/stdlib.h: In function ?int main()?:
/usr/include/stdlib.h:738: error: too few arguments to function ?int system(con?
exm2.cc:7: error: at this point in file
/usr/include/stdlib.h:738: error: too few arguments to function ?int system(con?
exm2.cc:8: error: at this point in file
回答by Pablo Santa Cruz
You can't use system()
without a char*
parameter.
system()
没有char*
参数就不能使用。
So these statements are wrong:
所以这些说法是错误的:
system();
system();
If you are not going to make anything, just don't put anything in there.
如果你不打算做任何事情,就不要在那里放任何东西。
回答by Lee Netherton
system() takes at one argument you could call it with an empty string:
system() 接受一个参数,您可以使用空字符串调用它:
#include <stdio.h>
#include <stdlib.h>
int main()
{
system("echo -n '1. Current Directory is '; pwd");
system("mkdir temp");
system("");
system("");
system("echo -n '3. Current Directory is '; pwd");
return 0;
}
But you may as well just leave those lines out :-)
但是你也可以把这些行去掉:-)
回答by Alpine
the system()
function requires a parameter.
Try removing the 7th and 8th line.
该system()
函数需要一个参数。尝试删除第 7 行和第 8 行。
#include <stdio.h>
#include <stdlib.h>
int main()
{
system("echo -n '1. Current Directory is '; pwd");
system("mkdir temp");
system("echo -n '3. Current Directory is '; pwd");
return 0;
}
回答by peoro
system
takes a const char*
. You call it 5 times, passing nothing to it twice.
system
需要一个const char*
. 你调用它 5 次,两次没有传递任何东西。