c++ 列出当前目录下的目录与文件

#include <iostream>
#include <dirent.h>
#include <cstring>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
std::string listFilesAndDirs(const char* path, int& len) {
    DIR* dirp = opendir(path);
    if (dirp == NULL) {
        return 0;
    }
    std::stringstream FileStream;
    int count = 0;
    struct dirent* direntp = readdir(dirp);
    while (direntp != NULL) {
        const char* name = direntp->d_name;
        
        if (strcmp(name, ".") != 0 && strcmp(name, "..") != 0) {
            if (direntp->d_type == DT_DIR) {
                FileStream<< "[DIR] " << name << std::endl;
            } else {
                FileStream << "[FILE] " << name << std::endl;
            }
            count++;
        }
        
        direntp = readdir(dirp);
    }
    
    closedir(dirp);
    len = count;
    return FileStream.str();
}
int main() {
    const char* path = "."; // 当前目录
    int len = 0;
    std::string strfile;
    strfile = listFilesAndDirs(path,len);
    std::cout<<strfile<<std::endl;
    std::cout << "len is: " <<len <<std::endl;
    return 0;
}

  

posted on 2023-11-18 01:37  lydstory  阅读(113)  评论(0)    收藏  举报

导航