main.cpp
#ifndef PHOTO_FILE_PROCESSOR_H #define PHOTO_FILE_PROCESSOR_H #include <iostream> #include <string> #include <vector> #include <dirent.h> #include <algorithm> #include <stdexcept> class PhotoFileProcessor { public: // 建構函式,初始化目錄路徑 explicit PhotoFileProcessor(const std::string& directory_path) : directoryPath(directory_path) {} // 獲取檔名(不帶副檔名)並按時間戳排序的實現 std::vector<std::string> getFilenamesSortedByTimestamp() const { DIR* dir = opendir(directoryPath.c_str()); if (dir == nullptr) { throw std::runtime_error("無法開啟目錄: " + directoryPath); } std::vector<std::pair<double, std::string>> fileTimestampPairs; struct dirent* entry; while ((entry = readdir(dir)) != nullptr) { std::string filename(entry->d_name); // 過濾掉"."和".."目錄 if (filename == "." || filename == "..") { continue; } // 去除副檔名 std::string filename_without_extension = removeExtension(filename); // 轉化成時間戳 try { double timestamp = extractTimestamp(filename_without_extension); fileTimestampPairs.emplace_back(timestamp, filename_without_extension); } catch (const std::runtime_error& e) { // 處理提取時間戳失敗的情況 std::cerr << "警告: " << e.what() << std::endl; } } closedir(dir); // 按時間戳排序 std::sort(fileTimestampPairs.begin(), fileTimestampPairs.end(), [](const std::pair<double, std::string>& a, const std::pair<double, std::string>& b) { return a.first < b.first; } ); // 提取排序後的檔名 std::vector<std::string> sortedFilenames; for (const auto& pair : fileTimestampPairs) { sortedFilenames.push_back(pair.second); } return sortedFilenames; } private: // 去除檔名中的副檔名的實現 std::string removeExtension(const std::string& filename) const { size_t last_dot = filename.find_last_of('.'); if (last_dot == std::string::npos) { return filename; // 如果沒有點,返回原始檔名 } return filename.substr(0, last_dot); } // 從檔名中提取時間戳的實現 double extractTimestamp(const std::string& filename) const { // 假設檔名是數字形式的時間戳,例如 "1234567890.jpg" try { return std::stod(filename); } catch (const std::invalid_argument& e) { throw std::runtime_error("無法從檔名中提取時間戳: " + filename); } } // 目錄路徑 std::string directoryPath; }; int main() { try { std::string directory_path = "/home/dongdong/2project/0data/NWPU/img"; // 替換為你的目錄路徑 PhotoFileProcessor processor(directory_path); std::vector<std::string> filenames = processor.getFilenamesSortedByTimestamp(); // 列印結果 for (const std::string& filename : filenames) { std::cout << filename << std::endl; } } catch (const std::exception& e) { std::cerr << "錯誤: " << e.what() << std::endl; } return 0; } #endif // PHOTO_FILE_PROCESSOR_H
CMakeLists.txt
cmake_minimum_required(VERSION 3.10) project(ImageUtilExample VERSION 1.0) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED True) # 新增可執行檔案 add_executable(ImageUtilExample main.cpp ) # 如果需要,連結其他庫