Reputation: 608
Ok it might sounds dumb, but I couldn't figure out a way to pass int/char into this system call
here is how I would like it to work
system ("cal %d %d", month, year);
I expect this will give me the following command on terminal "cal 3 2009
"
and the terminal will show me the calendar of March 2009.
But the compiler is complaining it has too many arguments
any ideas? I need to make this method system ("cal ")
return me a dynamic calendar.
Notes: cal
take the argument cal month year
Upvotes: 4
Views: 5479
Reputation: 399813
You need to build the proper command line string, system()
won't do it for you:
char cmd[64];
snprintf(cmd, sizeof cmd, "cal %d %d", month, year);
system(cmd);
The usual caveats about buffer overflow apply, although in this particular case when both arguments are integers you should be fairly safe.
Upvotes: 8
Reputation: 9026
try
#include <stdlib.h>
#include <stdio.h>
int main()
{
char command_buf [20];
const int month = 3;
const int year = 2009;
snprintf(command_buf, sizeof(command_buf), "cal %d %d", month, year);
system(command_buf);
}
Upvotes: 1
Reputation: 15406
Basically, just do your printf thing out of the system call :
char my_cmd[MAX_SIZE];
snprintf(my_cmd, MAX_SIZE, "cal %d %d", month, year);
system(my_cmd);
Upvotes: 3
Reputation:
char
string[64];
sprintf( string, "cal %d %d", month, year );
system( string );
Upvotes: 0
Reputation: 143795
This happens because you are assuming system behaves like printf, which is not the case. To obtain what you need, you have first to obtain the substitution through sprintf into a buffer, then pass this buffer to system.
Be careful though, this can become a potential security hole, because you are potentially allowing unknown parameters to be passed at command line execution. Also, you have to be careful that the temporary buffer you use is large enough to host your final string.
Upvotes: 1
Reputation: 2486
you have to format your command in a string before calling system with it, use snprintf for instance
Upvotes: 0
Reputation: 170499
You need to pass a string that already has all necessary transformations made. You can use sprintf() for producing such a string, just be careful with allocating a large enough buffer.
Upvotes: 1