在C中执行用户输入作为shell命令

时间:2016-10-06 07:10:43

标签: bash unix terminal

任何人都可以告诉我如何在shell中执行c程序输入作为命令吗?

我尝试使用以下代码

#include <stdio.h>


    void main()
    {
    int year,month;
    system("date");
    printf("Enter the month and year\n");
    scanf("%d%d",&month,&year);
    system("cal &&");
    printf("%d %d",month,year);
    system("ls");
    system("ps");
    }

必须打印用户提供的月份和年份的日历

谢谢

1 个答案:

答案 0 :(得分:0)

您可以将用户输入传递给bash,如下所示;

int year,month;
system("date");
printf("Enter the month and year\n");
scanf("%d%d",&month,&year);

char cmd[4096];
sprintf(cmd, "cal -m %d %d", month, year);
system(cmd);


printf("%d %d",month,year);
system("ls");
system("ps");

man cal;

-m month          显示指定的月份。如果将月份指定为十进制数字,则可以在后跟字母“f”或“p”分别表示该数字的下一个月或前一个月。

输出;

...

enter image description here

...
相关问题