How can I get the list of files in a directory using C or C++?

前端 未结 27 3833
情书的邮戳
情书的邮戳 2020-11-21 05:30

How can I determine the list of files in a directory from inside my C or C++ code?

I\'m not allowed to execute the ls command and parse the results from

27条回答
  •  不要未来只要你来
    2020-11-21 06:21

    I hope this code help you.

    #include 
    #include 
    #include 
    #include 
    using namespace std;
    
    string wchar_t2string(const wchar_t *wchar)
    {
        string str = "";
        int index = 0;
        while(wchar[index] != 0)
        {
            str += (char)wchar[index];
            ++index;
        }
        return str;
    }
    
    wchar_t *string2wchar_t(const string &str)
    {
        wchar_t wchar[260];
        int index = 0;
        while(index < str.size())
        {
            wchar[index] = (wchar_t)str[index];
            ++index;
        }
        wchar[index] = 0;
        return wchar;
    }
    
    vector listFilesInDirectory(string directoryName)
    {
        WIN32_FIND_DATA FindFileData;
        wchar_t * FileName = string2wchar_t(directoryName);
        HANDLE hFind = FindFirstFile(FileName, &FindFileData);
    
        vector listFileNames;
        listFileNames.push_back(wchar_t2string(FindFileData.cFileName));
    
        while (FindNextFile(hFind, &FindFileData))
            listFileNames.push_back(wchar_t2string(FindFileData.cFileName));
    
        return listFileNames;
    }
    
    void main()
    {
        vector listFiles;
        listFiles = listFilesInDirectory("C:\\*.txt");
        for each (string str in listFiles)
            cout << str << endl;
    }
    

提交回复
热议问题