opendir 与 readdir


https://blog.csdn.net/q278233370/article/details/99681142

输入一个目录,输出目录下面所有文件的大小时间戳

#include 
#include 
#include 
#include 
#include 
#include 
#include 

int get_file_size_time(const char *filename) {
    struct stat statbuf;
    if (stat(filename, &statbuf) == -1) {
        printf("Get stat on %s Error:%d\n",filename, strerror(errno));
        return -1;
    }
    if (S_ISDIR(statbuf.st_mode)) {
        printf("%s is a dir \n",filename);
        return 0;
    }
    if (S_ISREG(statbuf.st_mode)) {
        printf("%s size:%ld bytes\tmodified at %s",filename, statbuf.st_size, ctime(&statbuf.st_mtime));
        return 0;
    }
}

int main(int argc, char **argv) {
    DIR *dirp;
    struct dirent *direntp;
    char buf[80];
    if (argc != 2) {
        printf("Usage:%s filename\n\a", argv[0]);
        return -1;
    }
    if (-1 == get_file_size_time(argv[1]))
        return 0;
    if ((dirp = opendir(argv[1])) == NULL) {
        printf("Open Directory %s Error:%d\n", argv[1], strerror(errno));
        return -1;
    }
    while ((direntp = readdir(dirp))){
        sprintf(buf,"%s/%s",argv[1],direntp->d_name);
        printf("filename=%s\n",direntp->d_name);
        get_file_size_time(buf);
    }
    closedir(dirp);
    return 0;
}

在congfig下面的目录中查找一个.txt文件

#include 
#include 
#include 
#include <string>
#include <string.h>

using namespace std;

int GetProject(std::string* psProjectPath)
{
    int ret = -1;
    DIR *dir;
    struct dirent *ptr;
    if (dir=opendir("config"))
    {
        ret = 1;
        while ((ptr=readdir(dir)) != NULL)
        {
            if(ptr->d_type != DT_DIR) continue;
            if((strcmp(ptr->d_name,".") == 0) || (strcmp(ptr->d_name,"..") == 0)) continue;
            DIR *dir2;
            struct dirent *ptr2;
            char path[128];
            sprintf(path, "config/%s", ptr->d_name);
            cout << "path = " << ptr->d_name << endl;
            if (dir2=opendir(path))
            {
                while ((ptr2=readdir(dir2)) != NULL)
                {
                    if(ptr2->d_type != DT_REG) continue;
                    if(!strstr(ptr2->d_name, ".txt")) continue;
                    sprintf(path, "config/%s/%s", ptr->d_name, ptr2->d_name);
                    *psProjectPath = path;
                    ret = 0;
                    break;
                }
                closedir(dir2);
            }
       //    break;
        }
        closedir(dir);
    }
        return ret;
}
int main()
{
        string path;

        int ret = GetProject(&path);

        cout << "path = " << path << endl;

}