okistuff
okistuff

Reputation: 85

system(); not allowing me to pass in variables

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!

Upvotes: 1

Views: 74

Answers (2)

Roberto Caboni
Roberto Caboni

Reputation: 7490

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

Upvotes: 2

Acorn
Acorn

Reputation: 26066

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().

Upvotes: 2

Related Questions