呼叫外部程式並傳入資料,然後獲取輸出。需要用到dstring
(
// 編譯:gcc main.c dstring.c -o main
#include
// perror()
#include
// exit()
#include
// pipe() fork() close() stdout_fileno dup2() execl() read()
#include
// wait()
#include
// strlen()
#include
"dstring.h"
// 執行程式並獲取輸出
// 引數:程式命令
char
*run1
(char
* cmd)
pclose
(fp)
;// 返回讀取結果
return buf;
}// 執行程式並獲取輸出
// 引數:程式命令、傳遞給程式的資料(null 表示不傳遞資料)
char
*run2
(char
* cmd,
char
*in)if(
pipe
(fdo)==-
1)// 建立子程序
pid_t pid =
fork()
;if(pid ==-1
)else
if(pid ==0)
close
(fdo[1]
);}// 確保 fdi[0] 是 stdin
if(fdi[0]
!= stdin_fileno)
close
(fdi[0]
);}// 執行命令if(
execl
("/bin/sh"
,"sh"
,"-c"
, cmd,
null)==
-1)close
(fdo[1]
);close
(fdi[0]
);}else
}// 資料傳遞完畢
close
(fdi[1]
);// 建立動態字串
const
int buf_size =
1024
;char
* buf =
newds
(buf_size)
;// 讀取管道內容
while
((n =
read
(fdo[0]
,dsendp
(buf)
, buf_size)
)>0)
// 資料讀取完畢
close
(fdo[0]
);// 等等子程序結束
wait
(null);
// 返回讀取結果
return buf;}}
intmain()
1 程式元素 標準輸入輸出
一 1 字串變數 char name 20 字串宣告 c 庫函式 void memset void str,int c,size t n 複製字元 c 乙個無符號字元 到引數 str 所指向的字串的前 n 個字元。memset name,0,sizeof name 字串初始化 strcpy name...
程式競賽輸入輸出部分(標準的輸入和輸出)
freopen c out.txt r stdin 輸入freopen out.txt w stdout 輸出 也可以在程式執行時臨時修改 abc.exe.txt abc.exe out.txt 程式競賽題目的特點 只做三件事 1 讀入資料。2 計算結果。3 列印輸出。提示 競賽中,輸入輸出不要列印...
彙編 DOS功能呼叫 常用輸入輸出
ah 01h,輸入乙個字元並回顯 al 輸入的字元 說明 若按enter鍵,吸收的是回車符 cr 0dh或13 換行符 lf 不吸收 ah 07h,輸入乙個字元不回顯 al 輸入的字元 ah 02h,輸出乙個字元 dl 待輸出的字元 ah 09h,輸出字串 ds dx指向字串首位址 字串以 24h ...