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

วิธีสร้าง Directory Tree ด้วย C++ ใน Linux


ในส่วนนี้เราจะดูวิธีสร้าง Directory Tree (โครงสร้างโฟลเดอร์ซ้อนกัน) ด้วยโค้ด C++ ใน Linux ในเทอร์มินัล Linux เราสามารถพิมพ์คำสั่งแบบ "mkdir -p /dir/dir1/dir2" ได้ โดย -p ใช้ระบุว่าเป็น Parent (สร้างโฟลเดอร์ย่อยแบบ Recursive)

ในโค้ด C++ เราสามารถใช้ไลบรารีระบบของ Linux แล้วใช้คำสั่งเทอร์มินัลเป็น String Argument ของฟังก์ชัน system() เราสามารถสร้าง Directory Tree ได้แบบนี้

ตัวอย่าง

#include <bits/stdc++.h> #include <iostream> #include <sys/stat.h> #include <sys/types.h> using namespace std; int main() {    int status;    status = system("mkdir -p TP/My_Folder/test"); // สร้างไดเรกทอรี    if (status == -1)       cerr << "Error : " << strerror(errno) << endl;    else       cout << "Directories are created" << endl; }

ผลลัพธ์

Directories are created

ถ้าเราตรวจสอบด้วยตนเอง จะพบไดเรกทอรีภายในไดเรกทอรีปัจจุบัน