C语言遍历目录文件并排序

有时候需要遍历目录文件,但是默认的函数并不支持指定排序的功能,现在介绍一种排序的遍历目录方式,默认按照文件名的数字进行排序

window版本

string split_pathexe(string szFullPath)//获取文件名
{
    char szPath[MAX_PATH] = {0};
    char szDrive[MAX_PATH] = {0};
    char szDir[MAX_PATH] = {0};
    char szFileName[MAX_PATH] = {0};
    char szExt[MAX_PATH] = {0};
    _tsplitpath(szFullPath.c_str(), szDrive, szDir, szFileName, szExt);    
    return string(szFileName);
}

bool CompareRules(string x,  string y) // 排序回调函数,按照数字排序
{
    int nLeft, nRight;
    nLeft = atoi(split_pathexe(x).c_str());
    nRight = atoi(split_pathexe(y).c_str());
    return nLeft<nRight;
}

string GF_GetDirFile(char *szpath)//返回文件路径JSON格式,使用的jsoncpp,使用的时候自行稍作改动即可
{
    list<string> mylist; 
    list<string>::iterator iter; 

    Json::Value root;
    Json::FastWriter writer;
    
    char szDir[255];
    strcpy(szDir,szpath);
    strcat(szDir,"\\*");

    _finddata_t dir_info;
    _finddata_t file_info;
    intptr_t f_handle;
    char tmp_path[_MAX_PATH];
    if((f_handle = _findfirst(szDir, &dir_info)) != -1)
    {
        while(_findnext(f_handle, &file_info) == 0)
        {
            if(is_special_dir(file_info.name))
                continue;
            if(is_dir(file_info.attrib))//如果是目录,生成完整的路径
            {
                
            }
            else
            {
                strcpy(tmp_path, szDir);
                tmp_path[strlen(tmp_path) - 1] = '\0';
                strcat(tmp_path, file_info.name);//生成完整的文件路径
                string strPath;
                strPath = tmp_path;
                mylist.push_back(strPath);
                //root.append(tmp_path);
            }
        }
        _findclose(f_handle);//关闭打开的文件句柄,并释放关联资源,否则无法删除空目录
    }
    else
    {
        show_error();//若路径不存在,显示错误信息
    }
    mylist.sort(CompareRules);
    for (iter = mylist.begin(); iter != mylist.end();++iter)  
    {     
        root.append((*iter));
    } 
    string data = writer.write(root);
    return data;
}

linux版本,linux有现成的排序遍历函数 scandir,比windows要简单

string GF_GetDirFile(char *szpath)
{
    Json::Value root;
    Json::FastWriter writer;
    char childpath[4096];
    struct dirent **namelist;
    int n;
    n = scandir(szpath,&namelist,0,comp);
    if(n<0)
        return "";
    int Index = 0;
    while(Index<n)
    {
        if(strcmp(namelist[Index]->d_name,".")==0||strcmp(namelist[Index]->d_name,"..") ==0)
        {
            free(namelist[Index]);
            Index++;
            continue;
        }
        string str;
        sprintf(childpath,"%s%s",szpath,namelist[Index]->d_name);
        if(is_dir(childpath))
        {
        }
        else
        {
            root.append(childpath);
        }
        free(namelist[Index]);
        Index++;
    }
    free(namelist);
    string data = writer.write(root);
    return data;
}

猜你喜欢

转载自blog.csdn.net/jiachaofrms/article/details/85614567