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++;
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章