Namespaces
Variants

std:: system

From cppreference.net
Utilities library
定义于头文件 <cstdlib>
int system ( const char * command ) ;

调用主机环境的命令处理器(例如 /bin/sh , cmd.exe ),并以 command 作为参数。返回一个实现定义的值(通常是被调用程序返回的值)。

如果 command 是空指针,则检查主机环境是否存在命令处理器,当且仅当命令处理器存在时返回非零值。

目录

参数

command - 标识要在命令处理器中运行的命令的字符串。如果给定空指针,则检查命令处理器是否存在

返回值

实现定义值。如果 command 是空指针,当且仅当命令处理器存在时返回非零值。

注释

在POSIX系统上,返回值可通过 WEXITSTATUS WSTOPSIG 进行解析。

相关的POSIX函数 popen 使得调用者能够获取由 command 生成的输出。

在调用 std::system 之前,如果被调用的进程执行任何屏幕I/O操作,则必须显式刷新 std::cout

示例

#include <cstdlib>
#include <fstream>
#include <iostream>
int main()
{
    std::system("ls -l >test.txt"); // 执行 UNIX 命令 "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