ข้ามไปที่เนื้อหาหลัก

ไฟล์และไดเรกทอรีด้วยชุดไลบรารี boost

ต่อจาก ชุดไลบรารี date_time ของ Boost วันนี้เลยบันทึกเกี่ยวกับการจัดการไฟล์และไดเรกทอรีด้วยชุดไลบรารีของ boost สักนิด สำหรับชุดที่สนใจคือ filesystem สำหรับ filesystem เองหากพิจารณาแล้วมี class ที่น่าสนใจคือ path directory_entry directory_iterator recursive_directory_iterator file_status ที่อาจจะต้องใช้งานแล้วแต่กรณี แต่ที่ใช้ประจำเห็นคงหนีไม่พ้น path เนื่องจากเป็น class ที่ใช้ระบุตำแหน่งไฟล์นั้นเอง ส่วนที่เหลือจะเป็น operational functions ที่ใช้ร่วมกับ class ที่กล่าวไปแล้ว แต่ส่วนใหญ่จะใช้งานออปเจคของ path นั้นเอง มาดูตัวอย่างแรกกันดีกว่า
// directory.cpp
#include <iostream>
#include <string>
#include <boost/filesystem.hpp>

using namespace std;
using namespace boost::filesystem;

int main(){

string directory_path = "/tmp/test";

path p(directory_path);
if (exists(p))
cout << p << " exists" << endl;
else{
cout << p << " does not exist" << endl;
if (create_directory(p))
  cout << "create directory:" << directory_path << endl;
else
  cout << "can not create directory:" << directory_path << endl;
}

return 0;
}
จากตัวอย่างด้านบนเป็นการตรวจสอบว่ามีไดเรกทอรี /tmp/test ปรากฏอยู่หรือเปล่า หากไม่มีให้สร้างไดเรกทอรีขึ้นมาใหม่ ผลจากการทดสอบ

$ g++ directory.cpp -lboost_filesystem -lboost_system
$ ./a.out
"/tmp/test" does not exist
create directory:/tmp/test
$ ./a.out
"/tmp/test" exists

ลองดูตัวอย่างง่ายๆ อีกตัวอย่างหนึ่ง
// directory_1.cpp
#include <iostream>
#include <string>
#include <boost/filesystem.hpp>
using namespace std;
using namespace boost::filesystem;

int main(int argc, char** argv)
{
  if (argc < 2) {
      cerr << "type arg "<<endl;
      return -1;
  }

  path p (argv[1]);  

  if (exists(p)){
      if (is_regular_file(p))        
        cout << p << " size is " << file_size(p) << endl;
      else if (is_directory(p))
        cout << p << " is a directory" << endl;
      else
        cout << p << " neither a regular file nor a directory" <<endl;
    }
    else
      cout << p << " does not exist" << endl;

  return 0;
}

จากโคดด้านบนเป็นการตรวจสอบว่า path ที่ระบุไว้เป็นไฟล์หรือไดเรกทอรี หากเป็นไฟล์ให้แสดงขนาดออกมา

$ g++ directory_1.cpp -lboost_system -lboost_filesystem
$ ./a.out /tmp
"/tmp" is a directory
$ ./a.out /tmp/a
"/tmp/a" does not exist
$ touch /tmp/b
$ ./a.out /tmp/b
"/tmp/b" size is 0
$ echo "hello world" >> /tmp/c
$ ./list-1 /tmp/c
"/tmp/c" size is 12

นอกจากนี้ยังสามารถศึกษาเพิ่มเติมได้ที่ Boost Filesystem Tutorial

ความคิดเห็น