名稱空間
變體
操作

std::system

來自 cppreference.com
< cpp‎ | utility‎ | program
 
 
 
 
定義於標頭檔案 <cstdlib>
int system( const char* command );

呼叫宿主環境的命令處理器(例如 /bin/sh, cmd.exe),並傳入引數 command。返回一個實現定義的值(通常是所呼叫程式返回的值)。

如果 command 是空指標,則檢查宿主環境是否有一個命令處理器,並且僅當命令處理器存在時才返回一個非零值。

目錄

[編輯] 引數

command - 標識要在命令處理器中執行的命令的字串。如果給定空指標,則檢查命令處理器是否存在。

[編輯] 返回值

實現定義的值。如果 command 是空指標,則僅當命令處理器存在時才返回非零值。

[編輯] 注意

在 POSIX 系統上,返回值可以使用 WEXITSTATUSWSTOPSIG 進行分解。

相關的 POSIX 函式 popen 可讓呼叫者獲取 command 生成的輸出。

如果在呼叫 std::system 之前,派生的程序執行任何螢幕 I/O,則 std::cout 也需要顯式重新整理。

[編輯] 示例

#include <cstdlib>
#include <fstream>
#include <iostream>
 
int main()
{
    std::system("ls -l >test.txt"); // executes the UNIX command "ls -l >test.txt"
    std::cout << std::ifstream("test.txt").rdbuf();
}

可能的輸出

total 16
-rwxr-xr-x 1 2001 2000 8859 Sep 30 20:52 a.out
-rw-rw-rw- 1 2001 2000  161 Sep 30 20:52 main.cpp
-rw-r--r-- 1 2001 2000    0 Sep 30 20:52 test.txt

[編輯] 參閱

C 文件 關於 system