[問題] 請問簡單的呼叫外部程式

看板C_and_CPP (C/C++)作者 (機機勳)時間15年前 (2011/06/01 14:33), 編輯推噓5(5014)
留言19則, 8人參與, 最新討論串1/1
如果我在程式裡需要用到另一個程式的功能 因此需要在兩個程式之間做引數之類的轉換 要怎麼做呢? ex: 我要呼叫abc.exe這個程式 system("abc.exe"); 但是我希望也能傳個字串或數值給abc.exe作運算後 ,再傳個字串或數值回來這個程式,請問如何寫呢? 原程式 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> int main(){ system("abc.exe 5"); return 0; } 程式abc.exe #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> int main(int k){ int t; t=k+1; printf("%d\n",k); printf("hello"); return 0; } 最後printf出來的結果: 3 hello 請問我哪個地方寫錯了呢? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.4.200

06/01 14:36, , 1F
system("abc.exe 參數1 參數2"); 接收結果,簡單一點
06/01 14:36, 1F

06/01 14:37, , 2F
就把結果寫入檔案,另外一個程式去查詢檔案內容即可
06/01 14:37, 2F

06/01 14:39, , 3F
謝謝 試試看
06/01 14:39, 3F
※ 編輯: OoShiunoO 來自: 140.112.4.200 (06/01 14:49)

06/01 15:38, , 4F
GOOGLE→ int main(int argc, char* argv[])
06/01 15:38, 4F

06/01 15:47, , 5F
可以藉由argv 和sprintf出一個字串,再放入system.
06/01 15:47, 5F

06/01 15:47, , 6F
這樣彈性上升很多
06/01 15:47, 6F

06/01 20:54, , 7F
那abc.exe執行的結果, 可以在程式中取得嗎?
06/01 20:54, 7F

06/01 21:26, , 8F
有點不清楚,再講請楚點
06/01 21:26, 8F

06/01 21:35, , 9F
喔,我懂了,abc要這樣寫int main(int argc,char *argv[])
06/01 21:35, 9F

06/01 21:36, , 10F
printf("%d\n",k);->printf("%s\n",argv[1]);
06/01 21:36, 10F

06/01 21:41, , 11F
如果執行結果只是整數會比較好處理
06/01 21:41, 11F

06/01 21:41, , 12F
如果是比較複雜的資料,就要寫到檔案,或者用IPC來傳
06/01 21:41, 12F

06/02 15:29, , 13F
執行的結果可以用popen(),可是windows不知道有沒有這函數
06/02 15:29, 13F

06/02 15:33, , 14F
popen是標準函式 應該都會有
06/02 15:33, 14F

06/02 16:59, , 15F
popen 不是標準裡的呀 囧
06/02 16:59, 15F

06/02 17:03, , 16F
我搞錯了 orz 標準類似的是 freopen
06/02 17:03, 16F

06/02 17:26, , 17F
感謝版主<n.n>
06/02 17:26, 17F

06/02 17:47, , 18F
VC 可以用 _popen 原始碼在 popen.c
06/02 17:47, 18F

06/02 17:49, , 19F
對應的 Windows API 是 CreateProcess 跑 cmd.exe /c
06/02 17:49, 19F
文章代碼(AID): #1DvTqY4e (C_and_CPP)
文章代碼(AID): #1DvTqY4e (C_and_CPP)