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 << "\nRunning file ";
system("./a.out");
return 0;
}
system()與使用庫函數:
system()在Windows操作係統中的一些常見用法是:用於執行暫停命令並使屏幕/終端等待按鍵的係統(“pause”)和用於使屏幕/終端清晰的係統(“cls”)。
但是,由於以下原因,應避免調用係統命令:
- 這是一個非常昂貴且占用大量資源的函數調用
- 它不是便攜式的:使用system()會使該程序非常不可移植,即,僅適用於在係統級別具有暫停命令的係統,例如DOS或Windows。但不是Linux,MAC OSX和大多數其他軟件。
讓我們用一個簡單的C++代碼使用system(“pause”)輸出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 OS中上述程序的輸出:
Hello World! Press any key to continue…
該程序取決於操作係統,並使用以下繁重的步驟。
- 它掛起您的程序,同時調用操作係統以打開操作係統 shell 。
- 操作係統找到暫停並分配內存以執行命令。
- 然後,它重新分配內存,退出操作係統並恢複程序。
除了使用係統(“pause”),我們還可以使用在C /C++中本地定義的函數。
讓我們舉一個簡單的示例,用cin.get()輸出Hello World:
// 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!
因此,我們看到,係統(“pause”)和cin.get()實際上都在等待按鍵被按下,但是cin.get()不依賴於操作係統,並且它也不遵循上述步驟來暫停程序。同樣,使用C語言,getchar()可用於暫停程序,而無需打印消息“按任意鍵繼續…”。
檢查我們是否可以在操作係統中使用system()運行命令的常用方法?
如果我們使用空指針代替命令參數的字符串,則如果命令處理器存在(或係統可以運行),則係統返回非零值。否則返回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;
}
請注意,由於大多數在線編譯器(包括GeeksforGeeks IDE)都禁用了“係統”命令,因此上述程序可能無法在在線編譯器上運行。
注:本文由純淨天空篩選整理自 system() in C/C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。