Patryk
Patryk

Reputation: 24092

How to check how many files are there in a folder?

I would like to check how many files are there in the specified directory. For instance I would have a directory next to my .exe called resources and I would like to check how many of .txt files are located in it.

How this can be done in C++ in Windows?

Upvotes: 1

Views: 733

Answers (3)

Software_Designer
Software_Designer

Reputation: 8587

This MS Windows code lists all .txt files in C:. To list all other files, change strcpy(DirSpec, "c:\\*.txt") to strcpy(DirSpec, "c:\\*") .

#include <stdio.h> 
#include <stdlib.h> 
#define _WIN32_WINNT 0x0501 
#include <windows.h> 
#define BUFSIZE MAX_PATH 

int main(int argc, char *argv[]) 
{ 
    WIN32_FIND_DATA FindFileData; 
    HANDLE hFind = INVALID_HANDLE_VALUE; 
    DWORD dwError; 
    LPSTR DirSpec;
    unsigned int nFiles=0;
    DirSpec = (LPSTR) malloc (BUFSIZE); 
    strcpy(DirSpec, "c:\\*.txt"); 

    printf ("Current directory : %s\n\n", DirSpec); 

    hFind = FindFirstFile(DirSpec, &FindFileData); 
    if (hFind == INVALID_HANDLE_VALUE) 
    { 
        printf ("incorrect Handle : %u.\n", GetLastError()); 
        return (-1); 
    } 
    else 
    { 
        printf ("%s\n", FindFileData.cFileName); 


        while ( FindNextFile (hFind, &FindFileData) != 0) 
        { 
             nFiles++;
             printf ("%s\n", FindFileData.cFileName); 
        } 

        dwError = GetLastError(); 
        FindClose(hFind); 

        printf ("\n %d files found.\n\n", nFiles); 

        if (dwError != ERROR_NO_MORE_FILES) 
        { 
             printf ("FindNextFile Error.\n", dwError); 
             return (-1); 
        } 
    } 
    free(DirSpec); 
   return (0); 
}

Upvotes: 0

Adam Rosenfield
Adam Rosenfield

Reputation: 400274

This depends on the operating system. On Windows, you would use FindFirstFile and FindNextFile to enumerate the directory contents, using an appropriate filter such as "*.txt". Don't foget to call FindClose when you're done.

On Unix-based operating systems, you would use opendir(3) and readdir(3) to enumerate the directory contents. You'll have to filter the file names yourself. Don't forget to call closedir(3) when you're done.

Upvotes: 3

Harper Shelby
Harper Shelby

Reputation: 16583

I'd use boost::filesystem. There's even a sample program that has most of the work done for you.

Upvotes: 6

Related Questions