呼叫另一個執行程式 – 指令system("程式檔名")

依我所知副程式的定義可以為獨立於主程式的函式、外部程式。
利用stdlib.h裡面的函式system("程式檔名")來執行程式內容,程式執行完成後可回傳值或不回傳皆可,這取決於主程式是否需要其含式的執行結果數值。【e.g: system("hello.exe")】
撰寫一個練習範例,主程式計算雞兔同籠後,呼叫另一程式,運行另一程式印出三角形後,回傳一個數值給主程式,主程式再計算另一程式共印出多少星星。
(主:雞兔計算,函式system呼叫副程式,接收副程式數值,印出副程式星星數)
(副:被呼叫執行,輸入數值印三角形,回傳值給主程式)
主程式
#include<stdio.h>
#include<stdlib.h>
int main(){
  srand(time(0));
  int foot,head,ck,rb;
  do{
    printf("輸入腳數:");
    scanf("%d",&foot);
  }while((foot%2)!=0);
  printf("輸入頭數:");
  scanf("%d",&head);
  ck=(head*4-foot)/2;
  rb=head-ck;
  if(ck<0){
    printf("不合邏輯");
  }else{
    printf("CK=%d(2隻腳)\nRB=%d(4隻腳)\n",ck,rb);
  }

  printf("\nThis file will call hello.exe\n");
  int g=system("hello.exe");//g等於副程式執行完成後回傳的數值【return X;】
  int stars=0;
  printf("\n*********************************\nHere has get hello.exe return value\n\n");
  for(int p=0;p<g;++p){
    for(int o=0;o<p+1;++o){
      ++stars;
    }
  }
  printf("Total stars(form hello.exe): %d\n",stars);
  return 0;
}


副程式
#include<stdio.h>
#include<stdlib.h>
int main(){
        printf("\n****************************\nhello.exe start to work\n\n");
        int n,i,j;
        do{
                printf("Please key in a value(1~20):");
                scanf("%d",&n);
        }while(n>20 || n<=0);
        for(i=0;i<n;++i){
                for(j=0;j<i+1;++j){
                        printf("*");
                }
                printf("\n");
        }
        printf("hello.exe send the stars to test.exe\n");
        return n;
}

留言