从C ++程序调用linux命令

时间:2011-02-15 17:40:02

标签: c++

我编写以下简单的c ++程序,以了解如何从C ++程序调用Linux命令(使用系统命令)

请告知为什么我有C ++编译器的错误?我的计划有什么问题?

more 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

4 个答案:

答案 0 :(得分:9)

如果没有system()参数,则无法使用char*

所以这些陈述错误

system();
system();

如果你不打算做什么,就不要在里面放任何东西。

答案 1 :(得分:7)

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;
  }

但你也可以将这些内容排除在外: - )

答案 2 :(得分:5)

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;
}

exm2.cc是文件名吗? c ++程序源文件的扩展名为.cpp,因此它应为exm2.cpp
不是吗?

答案 3 :(得分:2)

system需要const char*。你称它为5次,两次没有通过它。

相关问题