How to pass int / char to system () Linux system call

Well, that might sound silly, but I couldn't figure out how to pass int / char to this system call

that's how i would like it to work

system ("cal %d %d", month, year);

I expect this to give me the following command on terminal " cal 3 2009"

and the terminal will show me the March 2009 calendar.

But the compiler complains that it has too many arguments

any ideas? I need to make this method system ("cal ")return me a dynamic calendar.

Notes: calaccept the argumentcal month year

+3
source share
7 answers

You need to create the correct command line, system()will not do this for you:

char cmd[64];

snprintf(cmd, sizeof cmd, "cal %d %d", month, year);
system(cmd);

, , , .

+8

, printf :

char my_cmd[MAX_SIZE];
snprintf(my_cmd, MAX_SIZE, "cal %d %d", month, year);
system(my_cmd);
+3

, . sprintf() , .

+1

, , printf, . , , sprintf , .

Be careful, this can become a potential security kernel, because you potentially allow unknown parameters to be passed when you run the command line. In addition, you must be careful that the temporary buffer used is large enough to accommodate the final line.

+1
source

to 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);
}
+1
source

you need to format your command in a line before calling the system with it, for example, use snprintf

0
source
char
  string[64];

sprintf( string, "cal %d %d", month, year );

system( string );
0
source

Source: https://habr.com/ru/post/1705633/


All Articles