C/C++ 用 _findfirst 與 _findnext 查找文件

頭文件
<io.h>


結構體

struct _finddata_t {
 unsigned attrib;
 time_t  time_create; 
 time_t  time_access; 
 time_t  time_write;
 _fsize_t size;
 char  name[260];
};

類型上:
time_t,其實就是long
而_fsize_t,就是unsigned long

結構體的數據成員上:
attrib,就是所查找文件的屬性:_A_ARCH(存檔)、_A_HIDDEN(隱藏)、_A_NORMAL(正常)、_A_RDONLY(只讀)、 _A_SUBDIR(文件夾)、_A_SYSTEM(系統)。
time_create、time_access和time_write分別是創建文件的時間、最後一次訪問文件的時間和文件最後被修改的時間。
size:文件大小
name:文件名。


用到的函數
1、_findfirst函數:long _findfirst(const char *, struct _finddata_t *);
2、_findnext函數:int _findnext(long, struct _finddata_t *);
3、_findclose()函數:int _findclose(long);

具體如何用、以及的相關例程,看[1]和[2]即可,詳細且有效,好評。


我寫的例程

void Recursive_file(string folderPath, string postfix);
void count_all_ans_in_this_file(string folderPath, string postfix);

Recursive_file();用於遞歸文件夾,在當前目錄遍歷完文件夾時,會調用count_all_ans_in_this_file();

count_all_ans_in_this_file();計算當前目錄所有非文件夾文件的信息,支持通配符postfix

例:
輸入 D:\c++\WC\*.cpp
folderPath 爲 D:\c++\WC
postfix 爲 *.cpp


代碼

void count_all_ans_in_this_file(string folderPath, string postfix){
    string fileName = folderPath + postfix;
    _finddata_t fileInfo;
    long HANDLE = _findfirst(fileName.c_str(), &fileInfo);

    if(HANDLE == -1L)//如果沒有該文件,直接結束即可,不是錯誤,不用報錯
    {
        return ;
    }
    do{
        string newPath = folderPath + '\\' + fileInfo.name;
        char ch[maxn_word_of_file_path];
        strcpy(ch, newPath.c_str());
        calculate_information(ch);
        display();
        init();
    }while(_findnext(HANDLE, &fileInfo) == 0);
    _findclose(HANDLE);
    return ;
}
void Recursive_file(string folderPath, string postfix){
    struct _finddata_t FileInfo;
    string strfind = folderPath + "\\*";
    long HANDLE = _findfirst(strfind.c_str(), &FileInfo);

    if(HANDLE == -1L)//文件不存在
    {
        printf("ERROR!!!文件不存在\n");
        exit(-1);
    }
    do{
        //判斷是否有子目錄
        if(FileInfo.attrib & _A_SUBDIR)//按位與不爲0,說明等於_A_SUBDIR
        {
            if((strcmp(FileInfo.name, ".") != 0) && (strcmp(FileInfo.name, "..") != 0))//判斷一下,如果 不是當前目錄 並且 不是父目錄,則遞歸該文件夾
            {
                string newPath = folderPath + "\\" + FileInfo.name;
                Recursive_file(newPath, postfix);
            }
        }
        else//當不是文件夾的時候,計算所有符合通配符的文件的信息,然後結束
        {
            //cout << folderPath.c_str() << "\\" << FileInfo.name << endl; //所有文件的路徑
            count_all_ans_in_this_file(folderPath, postfix);
            break;
        }
    }while(_findnext(HANDLE, &FileInfo) == 0);//遍歷所有文件夾
    _findclose(HANDLE);
    return ;
}

參考來源
[1] C++利用 _findfirst與_findnext查找文件的方法
[2] C++用 _findfirst 和 _findnext 查找文件
[3] C++ String 與 char* 相互轉換


如果要用Windows的api,可以參見這個視頻
https://www.bilibili.com/video/BV1Bb411e7av?p=11
用FindFirstFile(); 和 FindNextFile();

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章