jon
jon

Reputation: 953

How to call Linux command from C++ program?

I have written the following simple C++ program in order to learn how to call Linux command(s) from C++ program (by using the system command)

Please advise why I have the errors from the C++ compiler? What is wrong with my program?

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

Upvotes: 5

Views: 68685

Answers (4)

Lee Netherton
Lee Netherton

Reputation: 22482

system() takes one argument. So, you could call it with an empty string:

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

However, you may as well just leave those lines out.

Upvotes: 13

Alpine
Alpine

Reputation: 3858

the system() function requires a parameter. Try removing the 7th and 8th line.

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

Upvotes: 8

peoro
peoro

Reputation: 26060

system takes a const char*. You call it 5 times, passing nothing to it twice.

Upvotes: 3

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181270

You can't use system() without a char* parameter.

So these statements are wrong:

system();
system();

If you are not going to make anything, just don't put anything in there.

Upvotes: 13

Related Questions