【C++】#巨坑io.h# ubuntu中讀取指定目錄中的所有文件


摘要:ubuntu系統下,C++程序讀取指定文件夾中多個文件,保存文件名列表。文件名沒有規律且不考慮讀取子文件夾中的文件。

系統配置:ubuntu16.04, cmake編譯

 

首先安利一個函數,輸入string類型的文件夾路徑和vector類型的文件名列表,輸出vector類型的文件名列表。

具體可參考鏈接1鏈接2

#include <iostream>
#include <sys/types.h>
#include <dirent.h>
#include <vector>
#include <string>  // 如果strcmp()函數報錯,則使用<cstring>


void GetFileNames(string path,vector<string>& filenames)
{
    DIR *pDir;
    struct dirent* ptr;
    if(!(pDir = opendir(path.c_str()))){
        cout<<"Folder doesn't Exist!"<<endl;
        return;
    }
    while((ptr = readdir(pDir))!=0) {
        if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0){
            filenames.push_back(path + "/" + ptr->d_name);
    }
    }
    closedir(pDir);
}


int main() {
    vector<string> file_name;
    string path = "/home/gordon/data/slam6d_data/thermolab/pose";
 
    GetFileNames(path, file_name);
 
    for(int i = 0; i <file_name.size(); i++)
    {
        cout<<file_name[i]<<endl;
    }
 
    return 0;
}

 

再次,來介紹一個巨坑 —— io.h !

我一開始采用如下函數,該函數依賴io.h頭文件。代碼如下,

void getFilesAll(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) {
                    //files.push_back(p.assign(path).append("\\").append(fileinfo.name));
                    getFilesAll(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);
     }
}

第一次編譯后報錯:

error: aggregate ‘*********’ has incomplete type and cannot be defined

解決方法: struct _finddata_t fileinfo; 將struct去除, _finddata_t fileinfo; 

 

第二次編譯后報錯:

error: ‘_finddata_t’ was not declared in this scope

error: ‘_findfirst’ was not declared in this scope

error: ‘_A_SUBDIR’ was not declared in this scope

error: ‘_findnext’ was not declared in this scope

error: ‘_findclose’ was not declared in this scope

嘗試過很多方法,包括修改頭文件格式,修改CMakeLists.txt的include路徑,復制io.h文件到 /usr/include/ 路徑下,都失敗了。

最后在github的issue上看到有人提到,io.h 頭文件可能不兼容跨平台操作。在windows下這個頭文件運行穩定,但是在linux下這個頭文件不能正常運行。

巨坑吶!!!是真的不兼容嗎,還是存在其他問題?求高人指點!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM