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

前端 未结 27 3875
情书的邮戳
情书的邮戳 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:11

    Check out this class which uses the win32 api. Just construct an instance by providing the foldername from which you want the listing then call the getNextFile method to get the next filename from the directory. I think it needs windows.h and stdio.h.

    class FileGetter{
        WIN32_FIND_DATAA found; 
        HANDLE hfind;
        char folderstar[255];       
        int chk;
    
    public:
        FileGetter(char* folder){       
            sprintf(folderstar,"%s\\*.*",folder);
            hfind = FindFirstFileA(folderstar,&found);
            //skip .
            FindNextFileA(hfind,&found);        
        }
    
        int getNextFile(char* fname){
            //skips .. when called for the first time
            chk=FindNextFileA(hfind,&found);
            if (chk)
                strcpy(fname, found.cFileName);     
            return chk;
        }
    
    };
    

提交回复
热议问题