Latest web development tutorials

C 庫函數– system()

C 標準庫 - <stdlib.h> C標準庫- <stdlib.h>

描述

C庫函數int system(const char *command)把command指定的命令名稱或程序名稱傳給要被命令處理器執行的主機環境,並在命令完成後返回。

聲明

下面是system() 函數的聲明。

int system(const char *command)

參數

  • command --包含被請求變量名稱的C字符串。

返回值

如果發生錯誤,則返回值為-1,否則返回命令的狀態。

實例

下面的實例演示了system() 函數的用法,列出了unix 機上當前目錄下所有的文件和目錄。

#include <stdio.h>
#include <string.h>

int main ()
{
   char command[50];

   strcpy( command, "ls -l" );
   system(command);

   return(0);
} 

讓我們編譯並運行上面的程序,在unix 機上將產生以下結果:

drwxr-xr-x 2 apache apache 4096 Aug 22 07:25 hsperfdata_apache
drwxr-xr-x 2 railo railo 4096 Aug 21 18:48 hsperfdata_railo
rw------ 1 apache apache 8 Aug 21 18:48 mod_mono_dashboard_XXGLOBAL_1
rw------ 1 apache apache 8 Aug 21 18:48 mod_mono_dashboard_asp_2
srwx---- 1 apache apache 0 Aug 22 05:28 mod_mono_server_asp
rw------ 1 apache apache 0 Aug 22 05:28 mod_mono_server_asp_1280495620
srwx---- 1 apache apache 0 Aug 21 18:48 mod_mono_server_global

下面的實例演示了system() 函數的用法,列出了windows 機上當前目錄下所有的文件和目錄。

#include <stdio.h>
#include <string.h>

int main ()
{
   char command[50];

   strcpy( command, "dir" );
   system(command);

   return(0);
} 

讓我們編譯並運行上面的程序,在windows 機上將產生以下結果:

a.txt
amit.doc
sachin
saurav
file.c

C 標準庫 - <stdlib.h> C標準庫- <stdlib.h>