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

File Globbing (Path Name Expansion) ใน Linux ด้วย C++

File Globbing คืออะไร?

File Globbing หรือ Path Name Expansion คือการขยายรูปแบบตัวอักษรแทน (Wildcard Patterns) ให้กลายเป็นรายชื่อไฟล์ที่ตรงกันใน Linux

Wildcard Patterns หลัก

Patternความหมายตัวอย่างที่ตรง
*0 หรือมากกว่าตัวอักษรใดๆfile* -> file, files, file2, file.txt
?ตัวอักษรใดๆ เพียง 1 ตัวfile? -> file1, fileA (แต่ไม่ใช่ file หรือ file12)
[...]ตัวอักษรใดๆ ในชุด (รองรับช่วงและการปฏิเสธ)file[1-3] -> file1, file2, file3; file[!2] -> file1, file3 (ไม่ใช่ file2)

ตัวอย่างการใช้งานใน Linux Shell

$ ls
file  file1  file01  file211  files
$ ls file*
file  file1  file01  file211  files
$ ls file?
file1
$ ls file[1-3]
file1  file01  file211
$ ls file[!2]
file  file1  file211

การใช้งานใน C++

C++ มาตรฐานไม่มี globbing ตรงๆ แต่สามารถใช้:

  • glob() จาก <glob.h> (POSIX)
  • std::filesystem::directory_iterator (C++17) พร้อม regex

ตัวอย่างด้วย glob()

#include <glob.h>
#include <iostream>
#include <vector>

int main() {
    glob_t glob_result;
    glob("file*", GLOB_TILDE, NULL, &glob_result);
    for (size_t i = 0; i < glob_result.gl_pathc; ++i)
        std::cout << glob_result.gl_pathv[i] << '\n';
    globfree(&glob_result);
    return 0;
}