c++之讀取資料夾中的檔案
阿新 • • 發佈:2021-06-28
目錄
前言
做對應於播放rosbag包的離線版本, 讀取資料夾中image和pcd來處理, 因此需要讀取資料夾下的影象檔案, 然後根據影象的名稱來讀取pcd.
程式碼
#include <iostream> #include <string> #include <vector> #include <fstream> #include <sstream> #include <dirent.h> // 查詢資料夾下的制定檔案, 如png, pcd檔案, 同時輸出的按照檔名排名 bool getFileNames(const std::string& path, const std::string& sub_name, std::vector<std::string>& file_name_v) { file_name_v.clear(); // find DIR* p_dir; struct dirent* ptr; if (!(p_dir = opendir(path.c_str()))) { WARN << "file path don't exist!" << REND; return false; } std::string file_name; while ((ptr = readdir(p_dir)) != 0) { file_name = ptr->d_name; if (file_name.find(sub_name) != -1) //沒有找到返回-1 { file_name_v.emplace_back(file_name); } } closedir(p_dir); if (file_name_v.empty()) { WARN << "no file in file path!" << REND; return false; } // TODO: 按照string方式排序, 如何按照int方式排序 std::sort(file_name_v.begin(), file_name_v.end()); return true; }
查詢path下的檔案, 保證該檔名包含sub_name, 最後對file_name_v進行排序.
bool offlinePattern(ros::NodeHandle& nh, cv::FileStorage& fs_reader) { std::string data_path; fs_reader["data_path"] >> data_path; if (data_path.empty()) { WARN << "data path is empty!" << REND; return false; } INFO << "data path: " << data_path << REND; fs_reader.release(); const std::string image_sub_name = "jpeg"; std::vector<std::string> image_file_name_v; if (!getFileNames(data_path, image_sub_name, image_file_name_v)) { return false; } INFO << "data files size: " << image_file_name_v.size() << REND; // process image and pcd one by one std::string image_file_name, pcd_file_name; cv::Mat input_image; pcl::PointCloud<pcl::PointXYZI>::Ptr input_cloud_ptr(new pcl::PointCloud<pcl::PointXYZI>); for (size_t i = 0; i < image_file_name_v.size(); ++i) { image_file_name = image_file_name_v[i]; int pose = image_file_name.find_first_of("."); std::string sub_name = image_file_name.substr(0, pose); pcd_file_name = sub_name + ".pcd"; input_image = cv::imread(data_path + "/" + image_file_name); pcl::io::loadPCDFile(data_path + "/" + pcd_file_name, *input_cloud_ptr); } }
使用std::string的函式提取image_file_name中的名字, 比如/home/test/11.png
, 則得到/home/test/11
這個值.
int pose = image_file_name.find_first_of(".");
std::string sub_name = image_file_name.substr(0, pose);
參考
注: 第二個參考是windows下的.