linux和Windows下讀取目錄下文件

void getAllFiles(string path, vector<string>& files, string fileType)
{
#ifdef OS_WIN
    // 文件句柄
    long hFile = 0;
    // 文件信息
    _finddata_t fileinfo;

    string p;
    hFile = _findfirst(p.assign(path).append("\\*" + fileType).c_str(), &fileinfo);
    if (hFile != -1)
    {
        do
        {
            // 保存文件的全路徑
            files.push_back(p.assign(path).append("\\").append(fileinfo.name));

    } while (_findnext(hFile, &fileinfo) == 0); //尋找下一個,成功返回0,否則-1

    _findclose(hFile);
}
#endif

#ifdef OS_LINUX
    DIR* dir = opendir(path.c_str());//打開指定目錄
    dirent* pFile = NULL;//定義遍歷指針
    string p;
    if (dir != NULL)
    {
        while ((pFile = readdir(dir)) != NULL)//開始逐個遍歷
        {
            //這裏需要注意,linux平臺下一個目錄中有"."和".."隱藏文件,需要過濾掉
            if (pFile->d_name[0] != '.')//d_name是一個char數組,存放當前遍歷到的文件名
            {
                files.push_back(p.assign(path).append("/").append(pFile->d_name));
            }
        }
    }
    closedir(dir);//關閉指定目錄
#endif
}

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