1

I'm trying to make something that compiles and runs .c files in one command. But I'm having a problem. I got the filename through the get_string(); under the_ cs50.h_ library.

And now I'm to give the system() function this command make {filename} by doing this

system("make %s", filename")

But it just gives this error back:

mac.c:18:23: error: too many arguments to function call, expected single argument '__command', have 2 arguments
    system("make %s", filename);
    ~~~~~~            ^~~~~~~~

I understand that It means that the system() function has too many arguments but I don't know any other way to add in the filename after make.

Here is a copy of the code I am using if you need to look at it more. Thanks! Click Here to go to the github page If you find a fix, either comment it or you can do a pull request at the github!

Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39
okistuff
  • 85
  • 1
  • 2
  • 7

2 Answers2

2

system() only takes a single parameter. You need to build up the string beforehand, and then pass it already built.

For that, you probably are looking for a function like sprintf().

Acorn
  • 24,970
  • 5
  • 40
  • 69
  • 1
    By any chance could I have an example on how to do it. Thanks! – okistuff May 07 '20 at 20:07
  • @TECHSCHOOL200000 The best you can do is search for questions about `sprintf` like [this one perhaps](https://stackoverflow.com/questions/2674312/how-to-append-strings-using-sprintf). – Acorn May 07 '20 at 22:31
2

That compilation error is raised because system() expects only one string argument.

If you need to make the command dependent to a parameter, first build it with sprintf:

char command[256];

sprintf(command, "make %250s", filename);
system (command);

The %250s format is to avoid that, in the unlikely case that filename is longer than 250 characters, we go out of bounds of command array.

A safer function allowing to limit the total length is snprintf:

snprintf(command, 255, "make %s", filename);
Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39