
- C 標準庫
- C 庫 - 首頁
- C 庫 - <assert.h>
- C 庫 - <complex.h>
- C 庫 - <ctype.h>
- C 庫 - <errno.h>
- C 庫 - <fenv.h>
- C 庫 - <float.h>
- C 庫 - <inttypes.h>
- C 庫 - <iso646.h>
- C 庫 - <limits.h>
- C 庫 - <locale.h>
- C 庫 - <math.h>
- C 庫 - <setjmp.h>
- C 庫 - <signal.h>
- C 庫 - <stdalign.h>
- C 庫 - <stdarg.h>
- C 庫 - <stdbool.h>
- C 庫 - <stddef.h>
- C 庫 - <stdio.h>
- C 庫 - <stdlib.h>
- C 庫 - <string.h>
- C 庫 - <tgmath.h>
- C 庫 - <time.h>
- C 庫 - <wctype.h>
- C 標準庫資源
- C 庫 - 快速指南
- C 庫 - 有用資源
- C 庫 - 討論
- C 程式設計資源
- C 程式設計 - 教程
- C - 有用資源
C 庫 - system() 函式
C 的stdlib 庫 system() 函式用於從 c/c++ 程式執行由字串 'command' 指定的作業系統命令。它返回一個整數狀態,指示命令執行的成功或失敗。
此函式依賴於作業系統。我們在 Windows 上使用 'system("dir")',在 Unix 上使用 'system("ls")' 來列出目錄內容。
注意:此函式列出在我們的系統上編譯時當前目錄的檔案。如果使用線上編譯器編譯,它只會顯示 'main main.c'。
語法
以下是 system() 函式的語法:
int system(const char *string)
引數
此函式接受一個引數:
string - 它表示指向空終止字串的指標,其中包含我們要執行的命令。
返回值
如果命令成功執行,則此函式返回 0。否則,它返回非零值。
示例 1
在此示例中,我們建立一個基本的 c 程式來演示 system() 函式的使用。
#include <stdio.h> #include <string.h> #include <stdlib.h> int main() { char command[50]; // Set the command to "dir" (list files and directories) strcpy(command, "dir"); //use the system fucntion to execute the command. system(command); return 0; }
輸出
以下是輸出,顯示當前目錄的列表:
05/10/2024 05:26 PM <DIR> . 05/10/2024 03:01 PM <DIR> .. 05/09/2024 01:57 PM 238 abort.c 05/09/2024 01:57 PM 131,176 abort.exe 05/09/2024 02:10 PM 412 abort2.c 05/09/2024 02:13 PM 131,175 abort2.exe 05/09/2024 02:23 PM 354 abort3.c 05/09/2024 02:23 PM 131,861 abort3.exe 05/09/2024 04:56 PM 399 atexit1.c 05/09/2024 04:56 PM 132,057 atexit1.exe 05/09/2024 05:30 PM 603 atexit2.c 05/09/2024 05:09 PM 132,078 atexit2.exe 05/09/2024 05:35 PM 612 atexit3.c 05/09/2024 05:35 PM 132,235 atexit3.exe 05/07/2024 11:01 AM 182 atof.cpp 05/07/2024 11:01 AM 131,175 atof.exe . . .
示例 2
讓我們建立另一個 c 程式並使用 system() 函式執行外部命令(echo 命令)。
#include <stdio.h> #include <string.h> int main() { char command[50]; // Set the command to print a message strcpy(command, "echo Hello, World!"); // Execute the command system(command); return 0; }
輸出
以下是輸出:
Hello, World!
廣告