c++ 读取文件夹下所有的文件名

sort会将文件名排序,当然这个只限数字文件名

不是数字文件名的话,可以删去sort

void getFiles(std::string path, std::vector<std::string>  &files) {
    struct _finddata_t filefind;
    intptr_t hfile = 0;
    std::string s;
    if ((hfile = _findfirst(s.assign(path).append("/*").c_str(), &filefind)) != -1) {
        do  {
            if (filefind.attrib == _A_SUBDIR) {
                if (strcmp(filefind.name, ".") && strcmp(filefind.name, "..")){
                    getFiles(s.assign(path).append("/").append(filefind.name), files);
                }
            }
            else {
                //files.push_back(s.assign(path).append("/").append(filefind.name)); //完整路径
                files.push_back(filefind.name);  //只有文件名
            }
        } while (_findnext(hfile, &filefind) == 0);
    } _findclose(hfile);
}

bool cmp(string a, string b)
{
    int len1 = a.length(), len2 = b.length();
    int a_int = 0, b_int = 0;
    for (int i = 0; i < max(len1, len2); i++)
    {
        if (i < len1 && a[i] != '.' && a[i] != 'p' && a[i] != 'c' && a[i] != 'd')
        {
            a_int *= 10;
            a_int += a[i] - '0';
        }
        if (i < len2 && b[i] != '.' && b[i] != 'p' && b[i] != 'c' && b[i] != 'd')
        {
            b_int *= 10;
            b_int += b[i] - '0';
        }
    }


    return a_int < b_int;
}

vector<string> pcd_name;
int main()
{
    string pcd_path = "E:/BaiduNetdiskDownload/1/pcd";
    getFiles(pcd_path, pcd_name);

    int len = pcd_name.size();
    sort(pcd_name.begin(), pcd_name.end(), cmp);
    for (int i = 0; i < len; i++)
        cout << pcd_name[i] << endl;

    return 0;
}
自己选择的路,跪着也要走完。朋友们,虽然这个世界日益浮躁起来,只要能够为了当时纯粹的梦想和感动坚持努力下去,不管其它人怎么样,我们也能够保持自己的本色走下去。
原文地址:https://www.cnblogs.com/WTSRUVF/p/15622858.html