Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

System() Function ใน C/C++


งานคือแสดงการทำงานของ system() ใน C/C++

system() function เป็นส่วนหนึ่งของ C/C++ standard library ใช้ส่งคำสั่งที่ execute ได้ใน command processor หรือ terminal ของ OS และคืนค่าหลังจาก command เสร็จสิ้น

<stdlib.h> หรือ <cstdlib> ต้อง include เพื่อเรียกฟังก์ชันนี้

Syntax

Syntax ดังนี้ −

int system(char command)

ฟังก์ชันคืนค่า 0 ถ้า command execute สำเร็จโดยไม่มี error

ตัวอย่าง

Input: system("date")
Output: The current date is: Fri 12/27/2019

Explanation − ตัวอย่างแสดงการใช้ system function แสดง current date Output แสดงใน command processor ของ OS แสดงว่าใช้ system() รัน terminal commands ได้

ตัวอย่าง

Input: system("color a")
Output:

System() Function ใน C/C++

ตัวอย่างแสดงการใช้ system() โดยส่ง string ที่มี command ไป ตรงนี้ให้ "color a" เปลี่ยนสีข้อความใน command processor ทำงานได้ดี

แนวทางในโปรแกรมด้านล่าง −

  • สร้างตัวแปร char array cmd[10] เก็บ commands
  • ใช้ strcpy() เก็บ command ที่ต้องการลง string (include <string.h>)
  • ส่ง string นั้นเข้า system function

Algorithm

Start
Step 1-> In function main()
    Declare a char cmd[10]
    Call function strcpy(cmd, "dir")
    Call function system(cmd)
Stop

ตัวอย่าง

#include <iostream>
#include<stdlib.h>
#include<string.h>
using namespace std;
int main() {
    char cmd[10];
    strcpy(cmd,"dir");
    system(cmd);
    return0;
}

ผลลัพธ์

ถ้ารันโค้ดด้านบนจะได้ output −

12/25/2019 10:04 AM  .
12/25/2019 06:33 AM  ..
12/24/2019 09:56 AM  bin
12/25/2019 10:04 AM 183 main.cpp
12/25/2019 10:04 AM 1,564,278 main.exe
12/25/2019 06:33 AM 1,046 main.o
12/24/2019 06:33 AM  obj
12/24/2019 06:36 AM 358 Test.layout
5 File 1,566,927 bytes
4 Dir 169,866,692,120 bytes free

ที่นี่เราส่ง "dir" command ให้ system function ดังนั้นมันจะแสดง directories ทั้งหมด

วิธีตรวจสอบว่า command processor มีอยู่ใน OS หรือไม่ −

ส่ง Null pointer เข้า system() ถ้า return non-zero แสดงว่ามี command processor ถ้า return 0 แสดงว่าไม่มีและไม่สามารถเรียก system() ได้

ตัวอย่าง

#include <iostream>
#include<stdlib.h>
using namespace std;
int main() {
    if(system(Null))
        cout<<"Command Processor is present";
    else
        cout<<"Command processor is not present";
    return 0;
}