system()用于从C/C++程序调用操作系统命令。
int system(const char *command);
注: stdlib。呼叫系统需要包括h或cstdlib。
如果操作系统允许,我们可以使用system()执行任何可以在终端上运行的命令。例如,我们可以在Windows上调用system(“dir”)和system(“ls”)来列出目录的内容。
编写一个C/C++程序来编译和运行其他程序? 我们可以使用system()从程序中调用gcc。请参阅下面为Linux编写的代码。我们可以轻松地将代码更改为在windows上运行。
// A C++ program that compiles and runs another C++ // program #include <bits/stdc++.h> using namespace std; int main () { char filename[100]; cout << "Enter file name to compile " ; cin.getline(filename, 100); // Build command to execute. For example if the input // file name is a.cpp, then str holds "gcc -o a.out a.cpp" // Here -o is used to specify executable file name string str = "gcc " ; str = str + " -o a.out " + filename; // Convert string to const char * as system requires // parameter of type const char * const char *command = str.c_str(); cout << "Compiling file using " << command << endl; system (command); cout << "Running file " ; system ( "./a.out" ); return 0; } |
system()与使用库函数: 在Windows操作系统中,system()的一些常见用法是,system(“pause”)用于执行暂停命令并使屏幕/终端等待按键,system(“cls”)用于清除屏幕/终端。
但是,由于以下原因,应避免调用系统命令:
- 这是一个非常昂贵且资源密集的函数调用
- 它不便于携带 :使用system()会使程序非常不可移植,也就是说,这只适用于在系统级别具有暂停命令的系统,如DOS或Windows。但不是Linux、MAC OSX和大多数其他产品。
让我们用一个简单的C++代码输出hello World。 系统(“暂停”) :
// A C++ program that pauses screen at the end in Windows OS #include <iostream> using namespace std; int main () { cout << "Hello World!" << endl; system ( "pause" ); return 0; } |
上述程序在Windows操作系统中的输出:
Hello World! Press any key to continue…
这个程序依赖于操作系统,需要执行以下繁重的步骤。
- 它会挂起您的程序,同时调用操作系统以打开操作系统外壳。
- 操作系统会找到暂停并分配内存来执行命令。
- 然后释放内存,退出操作系统并恢复程序。
除了使用系统(“暂停”),我们还可以使用在C/C++中本机定义的函数。
让我们举一个简单的例子,用cin输出Hello World。get():
// Replacing system() with library function #include <iostream> #include <cstdlib> using namespace std; int main () { cout << "Hello World!" << endl; cin.get(); // or getchar() return 0; } |
该程序的输出为:
Hello World!
因此,我们看到 系统(“暂停”) 和 辛。得到() 实际上是在等待按键,但是,cin。get()不依赖于操作系统,也不遵循上述步骤暂停程序。 类似地,在C语言中, getchar() 可用于暂停程序,而无需打印消息“按任意键继续…”。
检查是否可以在操作系统中使用system()运行命令的常用方法? 若我们传递null指针代替命令参数的字符串,若命令处理器存在(或系统可以运行),系统将返回非零。否则返回0。
// C++ program to check if we can run commands using // system() #include <iostream> #include <cstdlib> using namespace std; int main () { if ( system (NULL)) cout << "Command processor exists" ; else cout << "Command processor doesn't exists" ; return 0; } |
请注意,上述程序可能无法在联机编译器上运行,因为大多数联机编译器都禁用了系统命令,包括 Geeksforgeks IDE .
本文由 苏班卡·达斯。 如果你喜欢Geeksforgek,并想贡献自己的力量,你也可以写一篇文章,然后把你的文章发到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。