#include #include #include static void printHelp(); static bool countDirRecursively( const char *srcPath, int& numFiles, int& numDirs, double& totalBytes ); int main(int argc, char *argv[]) { /* printf("argc=%d\n", argc); for (int i = 0; i < argc; ++i) { printf("argv[%d]=\"%s\" (length=%d)\n", i, argv[i], strlen(argv[i])); } */ if (argc < 2) { printHelp(); return 1; } DWORD attr = GetFileAttributes(argv[1]); if (attr == INVALID_FILE_ATTRIBUTES) { printf("Illegal source directory.\n"); return (-1); } else if ((attr & FILE_ATTRIBUTE_DIRECTORY) == 0) { printf("Source is not a directory.\n"); return (-1); } int numFiles = 0; int numDirs = 0; double totalBytes = 0.; if (!countDirRecursively( argv[1], numFiles, numDirs, totalBytes )) return (-1); printf( "Files: %d, dirs: %d, bytes: %.0lf\n", numFiles, numDirs, totalBytes ); return 0; } static void printHelp() { printf( "Count recursively the number of files and\n" "subdirectories in a given directory, and their total size.\n" "Usage:\n" "\trcount directory\n" ); } static bool countDirRecursively( const char *srcPath, int& numFiles, int& numDirs, double& totalBytes ) { DWORD attr = GetFileAttributes(srcPath); if ( attr == INVALID_FILE_ATTRIBUTES || (attr & FILE_ATTRIBUTE_DIRECTORY) == 0 ) { return false; } char srcFile[MAX_PATH]; strcpy(srcFile, srcPath); size_t len = strlen(srcFile); if (len == 0) return false; if (srcFile[len-1] != '\\' && srcFile[len-1] != '/') strcat(srcFile, "\\"); int srcLen = strlen(srcFile); char pattern[MAX_PATH]; strcpy(pattern, srcFile); strcat(pattern, "*"); numFiles = 0; numDirs = 0; totalBytes = 0.; WIN32_FIND_DATA findData; HANDLE h; h = FindFirstFile(pattern, &findData); while (h != INVALID_HANDLE_VALUE) { if ( strcmp(findData.cFileName, "..") != 0 && strcmp(findData.cFileName, ".") != 0 ) { strcpy(srcFile + srcLen, findData.cFileName); printf("%s\n", srcFile); totalBytes += findData.nFileSizeLow; // findData.nFileSizeHigh if ( (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 ) { // Subdirectory ++numDirs; int nFiles = 0; int nDirs = 0; double bytes = 0.; if (!countDirRecursively( srcFile, nFiles, nDirs, bytes )) { printf( "Failed to process subdirectory %s\n", findData.cFileName ); return false; } numFiles += nFiles; numDirs += nDirs; totalBytes += bytes; } else { // Normal file ++numFiles; } } if (!FindNextFile(h, &findData)) break; } FindClose(h); return true; }