c語言用命令行編譯運行程序
Sometimes, we may need to execute Linux/Windows DOS commands through our C program. (Note: the code given below is compiled and executed on Linux GCC compiler, so here we are testing Linux commands only).
有時,我們可能需要通過C程序執行Linux / Windows DOS命令 。 (注意:下面給出的代碼是在Linux GCC編譯器上編譯和執行的 ,因此這里我們僅測試Linux命令)。
In the C programming standard library, there is a function named system () which is used to execute Linux as well as DOS commands in the C program.
在C編程標準庫中,有一個名為system()的函數,該函數用于執行Linux以及C程序中的DOS命令。
A command can be assigned directly to the function as an argument and command may also input from the user and then assigned to the function, function will send command to the operating system’s particular terminal like Linux terminal or DOS commands terminal to execute, and after the execution, you will get your output and program’s execution returns to the next statement written after the system() function.
可以將命令作為參數直接分配給函數,也可以從用戶輸入命令,然后將其分配給函數,函數會將命令發送到操作系統的特定終端(例如Linux終端或DOS命令終端)以執行,然后執行,您將獲得輸出,程序的執行返回到在system()函數之后編寫的下一條語句。
C中的system()函數 (system() function in C)
system() is a library function, which is defined in the stdlib.h header file. It is used to execute the Linux commands/Windows DOS commands.
system()是一個庫函數,該函數在stdlib.h頭文件中定義。 它用于執行Linux命令/ Windows DOS命令。
Syntax:
句法:
system(char *command);
Example:
例:
char *command = "ls";
system(command);
在C程序中運行Linux命令的程序 (Program to run Linux commands within C program)
#include <stdio.h>
#include <stdlib.h> //to use system()
#include <string.h> //to use strcpy()
int main()
{
char *command;
//executing ls command
strcpy(command, "ls");
printf("ls command...\n");
system(command);
//executing date command
strcpy(command, "date");
printf("date command...\n");
system(command);
return 0;
}
Output
輸出量
Please run this program at your machine
翻譯自: https://www.includehelp.com/c/executing-system-commands-using-c-program.aspx
c語言用命令行編譯運行程序