C++工程,c++递归读取目录下的所有文件,c++判断一个路径是目录还是文件,c++向文件写入一行,c++从文件读取一行,字符串分割strtok()

#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
// #include <time.h>

void read_path(std::string dir_path, std::ofstream &out_file) {
    DIR* dir = opendir(dir_path.c_str());//打开指定目录  
    dirent* p = NULL;//定义遍历指针  
    while((p = readdir(dir)) != NULL)//开始逐个遍历  
    {  
        //这里需要注意,linux平台下一个目录中有"."和".."隐藏文件,需要过滤掉  
        if(p->d_name[0] != '.')//d_name是一个char数组,存放当前遍历到的文件名  
        {  
            struct stat sb;
            std::string name = dir_path +"/"+ std::string(p->d_name);  
            lstat(name.c_str(), &sb);
            if(S_IFDIR == (sb.st_mode & S_IFMT)) {
                std::cout << name << " is dir" << std::endl;
                read_path(name, out_file);
            }else {
                out_file << 2 << "," <<(name+"\n").c_str();
            }
        }  
    }  
    closedir(dir);//关闭指定目录  
}

int main()
{
    std::string out_file_path = "1.txt";
    std::string dir_path = "/nfs-data/AIIT_DATA/image/reid_buy/ReID1-1-100/1-100_video";

    std::ofstream out_file(out_file_path);
    if(!out_file.is_open()) {
        std::cout << "time_map2txt open file:" << out_file_path << " failed!" << std::endl;
        return -1;
    }
    read_path(dir_path, out_file);
    out_file.close();

     
    std::fstream list_file(out_file_path);
    if(!list_file.is_open()) {
        std::cout << "file:" << out_file_path << "   is not open!" << std::endl;
        exit(-1);
    }
    std::string file;
    int i = 0;

    while(getline(list_file, file)) {
        char *p_str = (char*)file.data();
        if(!file.empty() && p_str[0] != '#') {
            char *p;
            const char *splite = ",";

            p = strtok(p_str, splite);
            std::string file_type_s = p;
            int file_type = stoi(file_type_s);
            
            p = strtok(NULL, splite);
            std::string file_name = p;
            std::cout << "[" << i << "] file_name:" << file_name << "   file_type:" << file_type << std::endl;  
            i++;
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章