笔记-CppCLR_WinForms操作遍历目录中,目录下的文件及目录

1.遍历目录下的所有文件


private: System::Void  UnderTheCatalogListFiles(const char * dir)
{

    intptr_t handle;
    _finddata_t findData;
    strcat((char *)dir, "*.*");        // 在要遍历的目录后加上通配符 

    handle = _findfirst(dir, &findData);    // 查找目录中的第一个文件
    if (handle == -1)
    {
        //cout << "Failed to find first file!\n";
        System::Windows::Forms::MessageBox::Show("Failed to find first file!", "错误", System::Windows::Forms::MessageBoxButtons::OK,
            System::Windows::Forms::MessageBoxIcon::Error);
        return;
    }

    do
    {

        if ((findData.attrib & _A_SUBDIR)
            &&(strcmp(findData.name, ".") == 0|| strcmp(findData.name, "..")==0))//不为"."或".."
            continue;

        if (findData.attrib & _A_SUBDIR)    // 是否是子目录
            //cout << findData.name << "\t\n";
            listBox1->Items->Add(Marshal::PtrToStringAnsi((IntPtr)(char *)findData.name) +"   ");
        else
            listBox1->Items->Add(Marshal::PtrToStringAnsi((IntPtr)(char *)findData.name)+"   "+findData.size+"Bytes");
            //cout << findData.name << "\t" << findData.size << endl;

    } while (_findnext(handle, &findData) == 0);    // 查找目录中的下一个文件

    _findclose(handle);    // 关闭搜索句柄

    System::Windows::Forms::MessageBox::Show("Done!", "完成", System::Windows::Forms::MessageBoxButtons::OK,
        System::Windows::Forms::MessageBoxIcon::Information);

}

2.遍历目录中的所有文件

private: System::Void  InTheCatalogListFiles(const char * dir)
{
    char dirNew[200];
    strcpy(dirNew, dir);
    strcat(dirNew, "\\*.*");    // 在目录后面加上"\\*.*"进行第一次搜索

    intptr_t handle;
    _finddata_t findData;

    handle = _findfirst(dirNew, &findData);
    if (handle == -1)        // 检查是否成功
        return;

    do
    {
        if (findData.attrib & _A_SUBDIR)
        {
            if (strcmp(findData.name, ".") == 0 || strcmp(findData.name, "..") == 0)
                continue;

            //cout << findData.name << "\t\n";
            listBox1->Items->Add(Marshal::PtrToStringAnsi((IntPtr)(char *)findData.name) + "   ");

            // 在目录后面加上"\\"和搜索到的目录名进行下一次搜索
            strcpy(dirNew, dir);
            strcat(dirNew, "\\");
            strcat(dirNew, findData.name);

            InTheCatalogListFiles(dirNew);
        }
        else
            //cout << findData.name << "\t" << findData.size << " bytes.\n";
            listBox1->Items->Add(Marshal::PtrToStringAnsi((IntPtr)(char *)findData.name) + "   " + findData.size + "Bytes");

    } while (_findnext(handle, &findData) == 0);

    _findclose(handle);    // 关闭搜索句柄
}

注:包含相关头文件

#include 
#include         // for strcat()
#include 

你可能感兴趣的:(Windows窗体应用)