c++ program list all files in the Directory

 1 /*c++ program list all files in the Directory
 2   2020-8-31
 3 */
 4 #include <iostream>
 5 #include <string>
 6 #include <vector>
 7 #include <fstream>
 8 #include <ros/ros.h>
 9 #include <geometry_msgs/Pose.h>
10 #include <dirent.h>
11 
12 //by reference : vector< >& 
13 void listFile(std::vector<std::string>& file_name){
14     struct dirent *entry;
15     std::string path("/home/robot/data/data.001");
16     DIR *dir=opendir(path.c_str());
17     if(!dir){
18         std::cout<<"can't open "<<path;
19         return;
20     }
21     while((entry=readdir(dir))!=NULL){
22     //get all file name in a directory without getting "." and ".." .. and .. are actually hard links in filesystems. 
They are needed so that you can specify relative paths, based on some reference path (consider "../sibling/file.txt").
Since these hard links are actually existing in the filesystem, it makes sense for readdir to tell you about them.
(actually the term hard link just means some name that is indistinguishable from the actual directory referred to:
they both point to the same inode in the filesystem).
23 if(std::string(entry->d_name)!="."&&std::string(entry->d_name)!=".."){ 24 //这里排查了很久的错误,若文件名不全会导致打不开文件! 25 file_name.push_back(path+"/"+std::string(entry->d_name)); 26 } 27 } 28 closedir(dir); 29 } 30 void print(const std::vector<geometry_msgs::Pose>& g){ 31 //iterating over std::vector 32 for (const auto& it:g){ 33 std::cout<<"pos.x:"<<it.position.x<<std::endl 34 <<"pos.y:"<<it.position.y<<std::endl 35 <<"pos.z:"<<it.position.z<<std::endl 36 <<"orientation.x:"<<it.orientation.x<<std::endl 37 <<"orientation.y:"<<it.orientation.y<<std::endl 38 <<"orientation.z:"<<it.orientation.z<<std::endl 39 <<"orientation.w:"<<it.orientation.w<<std::endl; 40 } 41 } 42 43 int main(){ 44 std::vector<std::string> file_name; 45 listFile(file_name); 46 47 std::sort (file_name.begin(),file_name.end(),std::greater<std::string>()); 48 //use vector 为了后期扩容 49 std::vector<geometry_msgs::Pose> gps_; 50 for(const auto& file : file_name){ 51 std::ifstream ifs (file.c_str(), std::ios::binary | std::ios::in); 52 std::cout<<file.c_str()<<std::endl; 53 if (ifs.is_open()) { 54 size_t size = 0; 55 ifs.read(reinterpret_cast<char *>(&size), sizeof(int)); 56 gps_.resize(size); 57 ifs.read(reinterpret_cast<char *>(&gps_[0]), sizeof(geometry_msgs::Pose) * size); 58 ifs.close(); 59 print(gps_); 60 } 61 else 62 std::cout<<"can't open"<<std::endl; 63 } 64 return 0; 65 }

 

posted @ 2020-08-31 13:44  蒙牛特仑苏  阅读(216)  评论(0编辑  收藏  举报