码迷,mamicode.com
首页 > 编程语言 > 详细

c++之读取文件夹中的文件

时间:2021-06-28 21:09:42      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:查找文件   details   排序   blog   rdo   struct   test   targe   pos   

前言

做对应于播放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下的.

c++之读取文件夹中的文件

标签:查找文件   details   排序   blog   rdo   struct   test   targe   pos   

原文地址:https://www.cnblogs.com/chrislzy/p/14942305.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!