1. 程式人生 > >讀取指定目錄下的所有文件(windows 和 linux 版)

讀取指定目錄下的所有文件(windows 和 linux 版)

char for files tdi hgfs oid 後綴 pau dst

筆者這裏用到了OpenCV,如果不需要用OpenCV代碼的話,可以將這部分代碼去掉即可。

windows vs2015環境代碼如下:

#include <io.h> // 結構體struct _finddata_t需要用到
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;

char * fileLoadPath = "E:\\ubshare\\Cars\\102051724100";
char * fileDstPath = "E:\\ubshare\\Cars\\testdir\\"
; void getFiles(string path, vector<string>& files) { //文件句柄 long hFile = 0; //文件信息 struct _finddata_t fileinfo; string p; if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1) { do { //如果是目錄,叠代之
//如果不是,加入列表 if ((fileinfo.attrib & _A_SUBDIR)) { if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0) getFiles(p.assign(path).append("\\").append(fileinfo.name), files); } else { files.push_back(p.assign(path).append(
"\\").append(fileinfo.name)); } } while (_findnext(hFile, &fileinfo) == 0); _findclose(hFile); } } int main() { vector<string> files; ////獲取該路徑下的所有文件 getFiles(fileLoadPath, files); int size = files.size(); for (int i = 0; i < size; i++) { string name = files[i].c_str() + strlen(fileLoadPath) + 1; // 從路徑名中取出文件名 cout << "files[i].c_str() = " << files[i].c_str() << ", name = " << name << endl; name.replace(name.find(".jpg"), 4, ".bmp"); // 將文件名的jpg後綴改為bmp後綴 Mat img = imread(files[i].c_str()); imshow(files[i].c_str(), img); string str = fileDstPath; str += name; imwrite(str, img); // 將圖片按指定格式存入指定路徑 } waitKey(0); return 0; }

linux版代碼如下:

#include <iostream>
#include <memory.h>
#include <stdio.h>
#include <stdlib.h>
#include <opencv2/opencv.hpp>
#include <dirent.h>

using namespace std;
using namespace cv;

string gFileLoadPath = "/mnt/hgfs/ubshare/Cars/102051724100/group2/";
string gFileDstPath = "/mnt/hgfs/ubshare/Cars/102051724100result/";

int main()
{
    DIR *dir = opendir(gFileLoadPath.c_str());
    if (dir == NULL)
    {
        cout << "opendir error" << endl;
        return -1;
    }

    struct dirent *entry;
    while ((entry = readdir(dir)) != NULL)
    {
        //if (entry->d_type == 4) continue; //It‘s dir
        cout << "name = " << entry->d_name << ", len = " << entry->d_reclen << ", entry->d_type = " << (int)entry->d_type << endl;
        string name = entry->d_name;
        string imgdir = gFileLoadPath + name;
        Mat img = imread(imgdir.c_str());
        imshow(entry->d_name, img);

        string resultdir = gFileDstPath + name;
        imwrite(resultdir.c_str(), img);
    }
    closedir(dir);
    waitKey(0);
    //system("pause");
    return 0;
}

讀取指定目錄下的所有文件(windows 和 linux 版)